Autoloader.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. /*
  3. * This file is part of the Predis package.
  4. *
  5. * (c) Daniele Alessandri <suppakilla@gmail.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Predis;
  11. /**
  12. * Implements a lightweight PSR-0 compliant autoloader.
  13. *
  14. * @author Eric Naeseth <eric@thumbtack.com>
  15. */
  16. class Autoloader
  17. {
  18. private $baseDir;
  19. private $prefix;
  20. /**
  21. * @param string $baseDirectory Base directory where the source files are located.
  22. */
  23. public function __construct($baseDirectory = null)
  24. {
  25. $this->baseDir = $baseDirectory ?: dirname(__FILE__);
  26. $this->prefix = __NAMESPACE__ . '\\';
  27. }
  28. /**
  29. * Registers the autoloader class with the PHP SPL autoloader.
  30. */
  31. public static function register()
  32. {
  33. spl_autoload_register(array(new self, 'autoload'));
  34. }
  35. /**
  36. * Loads a class from a file using its fully qualified name.
  37. *
  38. * @param string $className Fully qualified name of a class.
  39. */
  40. public function autoload($className)
  41. {
  42. if (0 !== strpos($className, $this->prefix)) {
  43. return;
  44. }
  45. $relativeClassName = substr($className, strlen($this->prefix));
  46. $classNameParts = explode('\\', $relativeClassName);
  47. require_once $this->baseDir.DIRECTORY_SEPARATOR.implode(DIRECTORY_SEPARATOR, $classNameParts).'.php';
  48. }
  49. }