autoloader.php 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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. * Append a slash ('/') to the given directory name, if it is not already there.
  140. *
  141. * @param string $directory The directory to append a slash to.
  142. * @return string
  143. */
  144. static function path_with_slash($directory) {
  145. return $directory[strlen($directory) - 1] == '/' ? $directory : $directory.'/';
  146. }
  147. /**
  148. * Convert a class name to a file name.
  149. *
  150. * Uppercase letters are converted to lowercase and prepended
  151. * by an underscore ('_').
  152. *
  153. * @param string $classname The class name to convert.
  154. * @return string
  155. */
  156. static function classname_to_filename($classname) {
  157. return strtolower(preg_replace('/(?<=.)([A-Z])/', '_\\1', $classname));
  158. }
  159. /**
  160. * Strip the root namespace from the beginning of a class name.
  161. *
  162. * @param string $classname The name of the class to strip the namespace from.
  163. * @return string The stripped class name.
  164. */
  165. private function strip_root_namespace($classname) {
  166. $begin = substr($classname, 0, strlen($this->root_namespace));
  167. if( $begin == $this->root_namespace )
  168. $classname = substr($classname, strlen($this->root_namespace));
  169. return $classname;
  170. }
  171. /**
  172. * Create the path to a class file.
  173. *
  174. * Any namespace prepended to the class name is split on '\', the
  175. * namespace levels are used to indicate directory names.
  176. *
  177. * @param string $classname The name of the class to create the file path of.
  178. */
  179. function create_path($classname) {
  180. $namespaces = array_filter(explode('\\', $classname));
  181. $dirs = array_map('self::classname_to_filename', $namespaces);
  182. $path = $this->root_directory;
  183. if( count($dirs) > 1 )
  184. $path .= implode('/', array_slice($dirs, 0, count($dirs) - 1)).'/';
  185. $path .= end($dirs).'.php';
  186. return strtolower($path);
  187. }
  188. /**
  189. * Load a class.
  190. *
  191. * Any namespace prepended to the class name is split on '\', the
  192. * namespace levels are used to indicate directory names.
  193. *
  194. * @param string $classname The name of the class to load, including pepended namespace.
  195. * @param bool $throw Whether to throw an exception if the class file does not exist.
  196. * @return bool
  197. * @throws FileNotFoundError If the class file does not exist.
  198. */
  199. function load_class($classname, $throw=null) {
  200. $classname = $this->strip_root_namespace($classname);
  201. $path = $this->create_path($classname);
  202. if( !file_exists($path) ) {
  203. if( $throw || ($throw === null && $this->throw_errors) )
  204. throw new FileNotFoundError($path);
  205. return false;
  206. }
  207. require_once $path;
  208. return true;
  209. }
  210. /**
  211. * Register the autoloader object to the SPL autoload stack.
  212. *
  213. * @param bool $prepend Whether to prepend the autoloader function to
  214. * the stack, instead of appending it.
  215. */
  216. function register($prepend=false) {
  217. spl_autoload_register(array($this, 'load_class'), true, $prepend);
  218. }
  219. }
  220. ?>