Autoloader.php 1.7 KB

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