AutoLoader.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. namespace OAuth\Common;
  3. /**
  4. * PSR-0 Autoloader
  5. *
  6. * @author ieter Hordijk <info@pieterhordijk.com>
  7. */
  8. class AutoLoader
  9. {
  10. /**
  11. * @var string The namespace prefix for this instance.
  12. */
  13. protected $namespace = '';
  14. /**
  15. * @var string The filesystem prefix to use for this instance
  16. */
  17. protected $path = '';
  18. /**
  19. * Build the instance of the autoloader
  20. *
  21. * @param string $namespace The prefixed namespace this instance will load
  22. * @param string $path The filesystem path to the root of the namespace
  23. */
  24. public function __construct($namespace, $path)
  25. {
  26. $this->namespace = ltrim($namespace, '\\');
  27. $this->path = rtrim($path, '/\\') . DIRECTORY_SEPARATOR;
  28. }
  29. /**
  30. * Try to load a class
  31. *
  32. * @param string $class The class name to load
  33. *
  34. * @return boolean If the loading was successful
  35. */
  36. public function load($class)
  37. {
  38. $class = ltrim($class, '\\');
  39. if (strpos($class, $this->namespace) === 0) {
  40. $nsparts = explode('\\', $class);
  41. $class = array_pop($nsparts);
  42. $nsparts[] = '';
  43. $path = $this->path . implode(DIRECTORY_SEPARATOR, $nsparts);
  44. $path .= str_replace('_', DIRECTORY_SEPARATOR, $class) . '.php';
  45. if (file_exists($path)) {
  46. require $path;
  47. return true;
  48. }
  49. }
  50. return false;
  51. }
  52. /**
  53. * Register the autoloader to PHP
  54. *
  55. * @return boolean The status of the registration
  56. */
  57. public function register()
  58. {
  59. return spl_autoload_register(array($this, 'load'));
  60. }
  61. /**
  62. * Unregister the autoloader to PHP
  63. *
  64. * @return boolean The status of the unregistration
  65. */
  66. public function unregister()
  67. {
  68. return spl_autoload_unregister(array($this, 'load'));
  69. }
  70. }