Autoloader.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. /**
  3. * Horde_Autoloader
  4. *
  5. * Manages an application's class name to file name mapping conventions. One or
  6. * more class-to-filename mappers are defined, and are searched in LIFO order.
  7. *
  8. * @author Bob Mckee <bmckee@bywires.com>
  9. * @author Chuck Hagenbuch <chuck@horde.org>
  10. * @category Horde
  11. * @package Autoloader
  12. */
  13. class Horde_Autoloader
  14. {
  15. private $_mappers = [];
  16. private $_callbacks = [];
  17. public function loadClass($className)
  18. {
  19. if ($path = $this->mapToPath($className)) {
  20. if ($this->_include($path)) {
  21. $className = strtolower($className);
  22. if (isset($this->_callbacks[$className])) {
  23. call_user_func($this->_callbacks[$className]);
  24. }
  25. return true;
  26. }
  27. }
  28. return false;
  29. }
  30. public function addClassPathMapper(Horde_Autoloader_ClassPathMapper $mapper)
  31. {
  32. array_unshift($this->_mappers, $mapper);
  33. return $this;
  34. }
  35. /**
  36. * Add a callback to run when a class is loaded through loadClass().
  37. *
  38. * @param string $class The classname.
  39. * @param mixed $callback The callback to run when the class is loaded.
  40. */
  41. public function addCallback($class, $callback)
  42. {
  43. $this->_callbacks[strtolower($class)] = $callback;
  44. }
  45. public function registerAutoloader()
  46. {
  47. // Register the autoloader in a way to play well with as many
  48. // configurations as possible.
  49. spl_autoload_register([$this, 'loadClass']);
  50. if (function_exists('__autoload')) {
  51. spl_autoload_register('__autoload');
  52. }
  53. }
  54. /**
  55. * Search registered mappers in LIFO order.
  56. */
  57. public function mapToPath($className)
  58. {
  59. foreach ($this->_mappers as $mapper) {
  60. if ($path = $mapper->mapToPath($className)) {
  61. if ($this->_fileExists($path)) {
  62. return $path;
  63. }
  64. }
  65. }
  66. }
  67. protected function _include($path)
  68. {
  69. return (bool)include $path;
  70. }
  71. protected function _fileExists($path)
  72. {
  73. return file_exists($path);
  74. }
  75. }