autoloader.php 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. <?php
  2. /**
  3. * A tool for autoloading PHP classes within a root directory and namespace.
  4. *
  5. * @author Taddeus Kroes
  6. * @date 13-07-2012
  7. */
  8. namespace webbasics;
  9. require_once 'base.php';
  10. /**
  11. * Object to automatically load classes within a root directory.
  12. *
  13. * Simple example: all classes are located in the 'classes' directory.
  14. * <code>
  15. * $loader = webbasics\Autoloader::getInstance();
  16. * $loader->addDirectory('classes'); // Add "classes" directory to global class path
  17. * $loader->loadClass('FooBar'); // Includes file "classes/FooBar.php"
  18. * </code>
  19. *
  20. * The Autoloader instance registers itself to the SPL autoload stack, so
  21. * that explicit 'include' statements for classes are not necessary anymore.
  22. * Therefore, the call to loadClass() in the example above is not necessary:
  23. * <code>
  24. * webbasics\Autoloader::getInstance()->addDirectory('classes');
  25. * $foobar = new FooBar(); // File "classes/FooBar.php" is automatically included
  26. * </code>
  27. *
  28. * Namespaces are assumed to indicate subdirectories:
  29. * <code>
  30. * webbasics\Autoloader::getInstance()->addDirectory('classes');
  31. * $bar = new foo\Bar(); // Includes "classes/foo/Bar.php"
  32. * $baz = new foo\bar\Baz(); // Includes "classes/foo/bar/Baz.php"
  33. * </code>
  34. *
  35. * To load classes within some namespace efficiently, directories can be
  36. * assigned to a root namespace:
  37. * <code>
  38. * $loader = webbasics\Autoloader::getInstance();
  39. * $loader->addDirectory('models', 'models');
  40. *
  41. * // File "models/Foo.php"
  42. * namespace models;
  43. * class Foo extends ActiveRecord\Model { ... }
  44. * </code>
  45. *
  46. * Exception throwing can be enabled in case a class does not exist:
  47. * <code>
  48. * $loader = webbasics\Autoloader::getInstance();
  49. * $loader->addDirectory('classes');
  50. * $loader->setThrowExceptions(true);
  51. *
  52. * try {
  53. * new Foo();
  54. * } catch (webbasics\AutoloadError $e) {
  55. * // "classes/Foo.php" does not exist
  56. * }
  57. * </code>
  58. *
  59. * @package WebBasics
  60. */
  61. class Autoloader extends Base implements Singleton {
  62. /**
  63. * Namespaces mapping to lists of directories.
  64. * @var array
  65. */
  66. private $directories = array('\\' => array());
  67. /**
  68. * Whether to throw an exception if a class file does not exist.
  69. * @var bool
  70. */
  71. private $throw_exceptions = false;
  72. /**
  73. * @see Singleton::$instance
  74. */
  75. private static $instance;
  76. /**
  77. * @see Singleton::getInstance()
  78. */
  79. static function getInstance() {
  80. if (self::$instance === null)
  81. self::$instance = new self;
  82. return self::$instance;
  83. }
  84. /**
  85. * Create a new Autoloader instance.
  86. *
  87. * Registers the {@link loadClass()} function to the SPL autoload stack.
  88. */
  89. private function __construct() {
  90. spl_autoload_register(array($this, 'loadClass'), true);
  91. }
  92. /**
  93. * Set whether to throw an exception when a class file does not exist.
  94. *
  95. * @param bool $throw Whether to throw exceptions.
  96. */
  97. function setThrowExceptions($throw) {
  98. $this->throw_exceptions = (bool)$throw;
  99. }
  100. /**
  101. * Whether an exception is thrown if a class file does not exist.
  102. *
  103. * @return bool
  104. */
  105. function getThrowExceptions() {
  106. return $this->throw_exceptions;
  107. }
  108. /**
  109. * Add a new directory to look in while looking for a class within the given namespace.
  110. */
  111. function addDirectory($directory, $namespace='\\') {
  112. $directory = self::pathWithSlash($directory);
  113. if ($namespace[0] != '\\')
  114. $namespace = '\\' . $namespace;
  115. if (!isset($this->directories[$namespace]))
  116. $this->directories[$namespace] = array();
  117. if (!in_array($directory, $this->directories[$namespace]))
  118. $this->directories[$namespace][] = $directory;
  119. }
  120. /**
  121. * Strip a namespace from the beginning of a class name.
  122. *
  123. * @param string $namespace The namespace to strip.
  124. * @param string $classname The name of the class to strip the namespace from.
  125. * @return string The stripped class name.
  126. */
  127. private static function stripNamespace($namespace, $classname) {
  128. if ($namespace != '\\')
  129. $namespace .= '\\';
  130. $begin = substr($classname, 0, strlen($namespace));
  131. if ($begin == $namespace)
  132. $classname = substr($classname, strlen($namespace));
  133. return $classname;
  134. }
  135. /**
  136. * Create the path to a class file.
  137. *
  138. * Any namespace prepended to the class name is split on '\', the
  139. * namespace levels are used to indicate directory names.
  140. *
  141. * @param string $classname The name of the class to create the file path of.
  142. */
  143. private static function createPath($classname) {
  144. $parts = array_filter(explode('\\', $classname));
  145. $path = '';
  146. if (count($parts) > 1)
  147. $path .= implode('/', array_slice($parts, 0, count($parts) - 1)) . '/';
  148. return $path . end($parts) . '.php';
  149. }
  150. /**
  151. * Load a class.
  152. *
  153. * Any namespace prepended to the class name is split on '\', the
  154. * namespace levels are used to indicate directory names.
  155. *
  156. * @param string $classname The name of the class to load, including pepended namespace.
  157. * @return bool Whether the class file could be found.
  158. * @throws ClassNotFoundError If the class file does not exist.
  159. * @todo Unit test reverse-order namespace traversal
  160. */
  161. function loadClass($classname) {
  162. // Prepend at least the root namespace
  163. if ($classname[0] != '\\')
  164. $classname = '\\' . $classname;
  165. // Find namespace directory
  166. $parts = array_filter(explode('\\', $classname));
  167. // Try larger namespaces first, getting smaller and smaller up to the global namespace
  168. for ($i = count($parts); $i >= 0; $i--) {
  169. $namespace = '\\' . implode('\\', array_slice($parts, 0, $i));
  170. // If the namespace is mapped to a list of directories, attempt to
  171. // load the class file from there
  172. if (isset($this->directories[$namespace])) {
  173. foreach ($this->directories[$namespace] as $directory) {
  174. $class = self::stripNamespace($namespace, $classname);
  175. $path = $directory . self::createPath($class);
  176. if (file_exists($path)) {
  177. require_once $path;
  178. return true;
  179. }
  180. }
  181. }
  182. }
  183. if ($this->throw_exceptions)
  184. throw new ClassNotFoundError($classname);
  185. return false;
  186. }
  187. }
  188. /**
  189. * Exception, thrown when a class file could not be found.
  190. */
  191. class ClassNotFoundError extends FormattedException {
  192. function __construct($classname) {
  193. parent::__construct('could not load class "%s"', $classname);
  194. }
  195. }
  196. ?>