autoloader.php 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. <?php
  2. /**
  3. *
  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 loaded class names.
  65. *
  66. * @var string
  67. * @todo implement this
  68. */
  69. private $root_namespace = '';
  70. /**
  71. * Whether to throw an exception when a class file does not exist.
  72. *
  73. * @var bool
  74. */
  75. private $throw_errors;
  76. /**
  77. * Create a new Autoloader instance.
  78. *
  79. * @param string $directory Root directory of the autoloader.
  80. * @param bool $throw Whether to throw an exception when a class file does not exist.
  81. */
  82. function __construct($directory, $throw=true) {
  83. $this->set_root_directory($directory);
  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. * Append a slash ('/') to the given directory name, if it is not already there.
  120. *
  121. * @param string $directory The directory to append a slash to.
  122. * @return string
  123. */
  124. static function path_with_slash($directory) {
  125. return $directory[strlen($directory) - 1] == '/' ? $directory : $directory.'/';
  126. }
  127. /**
  128. * Convert a class name to a file name.
  129. *
  130. * Uppercase letters are converted to lowercase and prepended
  131. * by an underscore ('_').
  132. *
  133. * @param string $classname The class name to convert.
  134. * @return string
  135. */
  136. static function classname_to_filename($classname) {
  137. return strtolower(preg_replace('/(?<=.)([A-Z])/', '_\\1', $classname));
  138. }
  139. /**
  140. * Create the path to a class file.
  141. *
  142. * Any namespace prepended to the class name is split on '\', the
  143. * namespace levels are used to indicate directory names.
  144. *
  145. * @param string $classname The name of the class to create the file path of.
  146. */
  147. function create_path($classname) {
  148. $namespaces = array_filter(explode('\\', $classname));
  149. $dirs = array_map('self::classname_to_filename', $namespaces);
  150. $path = $this->root_directory;
  151. if( count($dirs) > 1 )
  152. $path .= implode('/', array_slice($dirs, 0, count($dirs) - 1)).'/';
  153. $path .= end($dirs).'.php';
  154. return strtolower($path);
  155. }
  156. /**
  157. * Load a class.
  158. *
  159. * Any namespace prepended to the class name is split on '\', the
  160. * namespace levels are used to indicate directory names.
  161. *
  162. * @param string $classname The name of the class to load, including pepended namespace.
  163. * @param bool $throw Whether to throw an exception if the class file does not exist.
  164. * @return bool
  165. * @throws FileNotFoundError If the class file does not exist.
  166. */
  167. function load_class($classname, $throw=true) {
  168. $path = $this->create_path($classname);
  169. if( !file_exists($path) ) {
  170. if( !$throw || !$this->throw_errors )
  171. return false;
  172. throw new FileNotFoundError($path);
  173. }
  174. require_once $path;
  175. return true;
  176. }
  177. /**
  178. * Register the autoloader object to the SPL autoload stack.
  179. *
  180. * @param bool $prepend Whether to prepend the autoloader function to
  181. * the stack, instead of appending it.
  182. */
  183. function register($prepend=false) {
  184. spl_autoload_register(array($this, 'load_class'), true, $prepend);
  185. }
  186. }
  187. ?>