autoloader.php 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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 BasicWeb;
  10. require_once 'base.php';
  11. /**
  12. * Object that to automatically load classes within a root directory.
  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=php>
  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. Be sure to disable
  36. * exceptions on the previously added loaders!
  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', false)->register();
  46. * Autoloader::create('other_classes')->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 an exception, since 'other_classes/baz.php' does not exist
  50. * </code>
  51. *
  52. * @package BasicWeb
  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 $directory Root directory of the autoloader.
  79. * @param bool $throw Whether to throw an exception when a class file does not exist.
  80. */
  81. function __construct($directory, $throw=false) {
  82. $this->set_root_directory($directory);
  83. $this->set_throw_errors($throw);
  84. }
  85. /**
  86. * Set whether to throw an exception when a class file does not exist.
  87. *
  88. * @param bool $throw Whether to throw exceptions.
  89. */
  90. function set_throw_errors($throw) {
  91. $this->throw_errors = !!$throw;
  92. }
  93. /**
  94. * Whether an exception is thrown when a class file does not exist.
  95. *
  96. * @return bool
  97. */
  98. function get_throw_errors() {
  99. return $this->throw_errors;
  100. }
  101. /**
  102. * Set the root directory from which classes are loaded.
  103. *
  104. * @param string $directory The new root directory.
  105. */
  106. function set_root_directory($directory) {
  107. $this->root_directory = self::path_with_slash($directory);
  108. }
  109. /**
  110. * Get the root directory from which classes are loaded.
  111. *
  112. * @return string
  113. */
  114. function get_root_directory() {
  115. return $this->root_directory;
  116. }
  117. /**
  118. * Set the root namespace that loaded classes are expected to be in.
  119. *
  120. * @param string $directory The new root namespace.
  121. */
  122. function set_root_namespace($namespace) {
  123. // Assert that the namespace ends with a backslash
  124. if( $namespace[strlen($namespace) - 1] != '\\' )
  125. $namespace .= '\\';
  126. $this->root_namespace = $namespace;
  127. }
  128. /**
  129. * Get the root namespace that loaded classes are expected to be in.
  130. *
  131. * @return string
  132. */
  133. function get_root_namespace() {
  134. return $this->root_namespace;
  135. }
  136. /**
  137. * Append a slash ('/') to the given directory name, if it is not already there.
  138. *
  139. * @param string $directory The directory to append a slash to.
  140. * @return string
  141. */
  142. static function path_with_slash($directory) {
  143. return $directory[strlen($directory) - 1] == '/' ? $directory : $directory.'/';
  144. }
  145. /**
  146. * Convert a class name to a file name.
  147. *
  148. * Uppercase letters are converted to lowercase and prepended
  149. * by an underscore ('_').
  150. *
  151. * @param string $classname The class name to convert.
  152. * @return string
  153. */
  154. static function classname_to_filename($classname) {
  155. return strtolower(preg_replace('/(?<=.)([A-Z])/', '_\\1', $classname));
  156. }
  157. /**
  158. * Strip the root namespace from the beginning of a class name.
  159. *
  160. * @param string $classname The name of the class to strip the namespace from.
  161. * @return string The stripped class name.
  162. */
  163. private function strip_root_namespace($classname) {
  164. $begin = substr($classname, 0, strlen($this->root_namespace));
  165. if( $begin == $this->root_namespace )
  166. $classname = substr($classname, strlen($this->root_namespace));
  167. return $classname;
  168. }
  169. /**
  170. * Create the path to a class file.
  171. *
  172. * Any namespace prepended to the class name is split on '\', the
  173. * namespace levels are used to indicate directory names.
  174. *
  175. * @param string $classname The name of the class to create the file path of.
  176. */
  177. function create_path($classname) {
  178. $namespaces = array_filter(explode('\\', $classname));
  179. $dirs = array_map('self::classname_to_filename', $namespaces);
  180. $path = $this->root_directory;
  181. if( count($dirs) > 1 )
  182. $path .= implode('/', array_slice($dirs, 0, count($dirs) - 1)).'/';
  183. $path .= end($dirs).'.php';
  184. return strtolower($path);
  185. }
  186. /**
  187. * Load a class.
  188. *
  189. * Any namespace prepended to the class name is split on '\', the
  190. * namespace levels are used to indicate directory names.
  191. *
  192. * @param string $classname The name of the class to load, including pepended namespace.
  193. * @param bool $throw Whether to throw an exception if the class file does not exist.
  194. * @return bool
  195. * @throws FileNotFoundError If the class file does not exist.
  196. */
  197. function load_class($classname, $throw=null) {
  198. $classname = $this->strip_root_namespace($classname);
  199. $path = $this->create_path($classname);
  200. if( !file_exists($path) ) {
  201. if( $throw || ($throw === null && $this->throw_errors) )
  202. throw new FileNotFoundError($path);
  203. return false;
  204. }
  205. require_once $path;
  206. return true;
  207. }
  208. /**
  209. * Register the autoloader object to the SPL autoload stack.
  210. *
  211. * @param bool $prepend Whether to prepend the autoloader function to
  212. * the stack, instead of appending it.
  213. */
  214. function register($prepend=false) {
  215. spl_autoload_register(array($this, 'load_class'), true, $prepend);
  216. }
  217. }
  218. ?>