autoloader.php 6.4 KB

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