autoloader.php 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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 = new Autoloader('classes');
  16. * $loader->load_class('FooBar'); // Includes file 'classes/foo_bar.php'
  17. * </code>
  18. *
  19. * An Autoloader instance can register itself to the SPL autoload stack, so
  20. * that explicit 'include' statements for classes are not necessary anymore.
  21. * Applied to the example above:
  22. * <code>
  23. * $loader = new Autoloader('classes');
  24. * $loader->register();
  25. * $foobar = new FooBar(); // File 'classes/foo_bar.php' is automatically included
  26. * </code>
  27. *
  28. * Namespaces are assumed to indicate subdirectories:
  29. * <code>
  30. * Autoloader::create('classes')->register();
  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. * Multiple autoloaders can be registered at the same time:
  36. * <code>
  37. * <code>
  38. * File structure:
  39. * classes/
  40. * | foo.php // Contains class 'Foo'
  41. * other_classes/
  42. * | bar.php // Contains class 'Bar'
  43. * </code>
  44. * Autoloader::create('classes')->register();
  45. * Autoloader::create('other_classes', true)->register();
  46. * $foo = new Foo(); // Includes 'classes/foo.php'
  47. * $bar = new Bar(); // Includes 'other_classes/bar.php', since 'classes/bar.php' does not exist
  48. * $baz = new Baz(); // Throws a FileNotFoundError, since 'other_classes/baz.php' does not exist
  49. * </code>
  50. *
  51. * @package WebBasics
  52. */
  53. class Autoloader extends Base {
  54. /**
  55. * The root directory to look in.
  56. *
  57. * @var string
  58. */
  59. private $root_directory;
  60. /**
  61. * The namespace classes in the root directory are expected to be in.
  62. *
  63. * This namespace is removed from the beginning of loaded class names.
  64. *
  65. * @var string
  66. */
  67. private $root_namespace = '\\';
  68. /**
  69. * Whether to throw an exception when a class file does not exist.
  70. *
  71. * @var bool
  72. */
  73. private $throw_errors;
  74. /**
  75. * Create a new Autoloader instance.
  76. *
  77. * @param string $root_directory Root directory of the autoloader.
  78. * @param string $root_namespace Root namespace of classes loaded by the autoloader.
  79. * @param bool $throw Whether to throw an exception when a class file does not exist.
  80. */
  81. function __construct($root_directory, $root_namespace='\\', $throw=false) {
  82. $this->set_root_directory($root_directory);
  83. $this->set_root_namespace($root_namespace);
  84. $this->set_throw_errors($throw);
  85. }
  86. /**
  87. * Set whether to throw an exception when a class file does not exist.
  88. *
  89. * @param bool $throw Whether to throw exceptions.
  90. */
  91. function set_throw_errors($throw) {
  92. $this->throw_errors = !!$throw;
  93. }
  94. /**
  95. * Whether an exception is thrown when a class file does not exist.
  96. *
  97. * @return bool
  98. */
  99. function get_throw_errors() {
  100. return $this->throw_errors;
  101. }
  102. /**
  103. * Set the root directory from which classes are loaded.
  104. *
  105. * @param string $directory The new root directory.
  106. */
  107. function set_root_directory($directory) {
  108. $this->root_directory = self::path_with_slash($directory);
  109. }
  110. /**
  111. * Get the root directory from which classes are loaded.
  112. *
  113. * @return string
  114. */
  115. function get_root_directory() {
  116. return $this->root_directory;
  117. }
  118. /**
  119. * Set the root namespace that loaded classes are expected to be in.
  120. *
  121. * @param string $namespace The new root namespace.
  122. */
  123. function set_root_namespace($namespace) {
  124. // Assert that the namespace ends with a backslash
  125. if( $namespace[strlen($namespace) - 1] != '\\' )
  126. $namespace .= '\\';
  127. $this->root_namespace = $namespace;
  128. }
  129. /**
  130. * Get the root namespace that loaded classes are expected to be in.
  131. *
  132. * @return string
  133. */
  134. function get_root_namespace() {
  135. return $this->root_namespace;
  136. }
  137. /**
  138. * Convert a class name to a file name.
  139. *
  140. * Uppercase letters are converted to lowercase and prepended
  141. * by an underscore ('_').
  142. *
  143. * @param string $classname The class name to convert.
  144. * @return string
  145. */
  146. static function classname_to_filename($classname) {
  147. return strtolower(preg_replace('/(?<=.)([A-Z])/', '_\\1', $classname));
  148. }
  149. /**
  150. * Strip the root namespace from the beginning of a class name.
  151. *
  152. * @param string $classname The name of the class to strip the namespace from.
  153. * @return string The stripped class name.
  154. */
  155. private function strip_root_namespace($classname) {
  156. $begin = substr($classname, 0, strlen($this->root_namespace));
  157. if ($begin == $this->root_namespace)
  158. $classname = substr($classname, strlen($this->root_namespace));
  159. return $classname;
  160. }
  161. /**
  162. * Create the path to a class file.
  163. *
  164. * Any namespace prepended to the class name is split on '\', the
  165. * namespace levels are used to indicate directory names.
  166. *
  167. * @param string $classname The name of the class to create the file path of.
  168. */
  169. function create_path($classname) {
  170. $namespaces = array_filter(explode('\\', $classname));
  171. $dirs = array_map('self::classname_to_filename', $namespaces);
  172. $path = $this->root_directory;
  173. if (count($dirs) > 1)
  174. $path .= implode('/', array_slice($dirs, 0, count($dirs) - 1)).'/';
  175. $path .= end($dirs).'.php';
  176. return strtolower($path);
  177. }
  178. /**
  179. * Load a class.
  180. *
  181. * Any namespace prepended to the class name is split on '\', the
  182. * namespace levels are used to indicate directory names.
  183. *
  184. * @param string $classname The name of the class to load, including pepended namespace.
  185. * @param bool $throw Whether to throw an exception if the class file does not exist.
  186. * @return bool
  187. * @throws FileNotFoundError If the class file does not exist.
  188. */
  189. function load_class($classname, $throw=null) {
  190. $classname = $this->strip_root_namespace($classname);
  191. $path = $this->create_path($classname);
  192. if (!file_exists($path)) {
  193. if ($throw || ($throw === null && $this->throw_errors))
  194. throw new FileNotFoundError($path);
  195. return false;
  196. }
  197. require_once $path;
  198. return true;
  199. }
  200. /**
  201. * Register the autoloader object to the SPL autoload stack.
  202. *
  203. * @param bool $prepend Whether to prepend the autoloader function to
  204. * the stack, instead of appending it.
  205. */
  206. function register($prepend=false) {
  207. spl_autoload_register(array($this, 'load_class'), true, $prepend);
  208. }
  209. }
  210. ?>