Autoloader.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. * @author Daniele Alessandri <suppakilla@gmail.com>
  16. */
  17. class Autoloader
  18. {
  19. private $directory;
  20. private $prefix;
  21. private $prefixLength;
  22. /**
  23. * @param string $baseDirectory Base directory where the source files are located.
  24. */
  25. public function __construct($baseDirectory = __DIR__)
  26. {
  27. $this->directory = $baseDirectory;
  28. $this->prefix = __NAMESPACE__ . '\\';
  29. $this->prefixLength = strlen($this->prefix);
  30. }
  31. /**
  32. * Registers the autoloader class with the PHP SPL autoloader.
  33. */
  34. public static function register()
  35. {
  36. spl_autoload_register(array(new self, 'autoload'));
  37. }
  38. /**
  39. * Loads a class from a file using its fully qualified name.
  40. *
  41. * @param string $className Fully qualified name of a class.
  42. */
  43. public function autoload($className)
  44. {
  45. if (0 === strpos($className, $this->prefix)) {
  46. $parts = explode('\\', substr($className, $this->prefixLength));
  47. require($this->directory.DIRECTORY_SEPARATOR.implode(DIRECTORY_SEPARATOR, $parts).'.php');
  48. }
  49. }
  50. }