autoloader.php 6.5 KB

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