Commit 62641b42 authored by Taddeus Kroes's avatar Taddeus Kroes

Simplified Autoloader class into an easy-to-use singleton

parent c7d4d826
...@@ -15,163 +15,138 @@ require_once 'base.php'; ...@@ -15,163 +15,138 @@ require_once 'base.php';
* *
* Simple example: all classes are located in the 'classes' directory. * Simple example: all classes are located in the 'classes' directory.
* <code> * <code>
* $loader = new Autoloader('classes'); * $loader = webbasics\Autoloader::getInstance();
* $loader->loadClass('FooBar'); // Includes file 'classes/foo_bar.php' * $loader->addDirectory('classes'); // Add "classes" directory to global class path
* $loader->loadClass('FooBar'); // Includes file "classes/FooBar.php"
* </code> * </code>
* *
* An Autoloader instance can register itself to the SPL autoload stack, so * The Autoloader instance registers itself to the SPL autoload stack, so
* that explicit 'include' statements for classes are not necessary anymore. * that explicit 'include' statements for classes are not necessary anymore.
* Applied to the example above: * Therefore, the call to loadClass() in the example above is not necessary:
* <code> * <code>
* $loader = new Autoloader('classes'); * webbasics\Autoloader::getInstance()->addDirectory('classes');
* $loader->register(); * $foobar = new FooBar(); // File "classes/FooBar.php" is automatically included
* $foobar = new FooBar(); // File 'classes/foo_bar.php' is automatically included
* </code> * </code>
* *
* Namespaces are assumed to indicate subdirectories: * Namespaces are assumed to indicate subdirectories:
* <code> * <code>
* Autoloader::create('classes')->register(); * webbasics\Autoloader::getInstance()->addDirectory('classes');
* $bar = new Foo\Bar(); // Includes 'classes/foo/bar.php' * $bar = new foo\Bar(); // Includes "classes/foo/Bar.php"
* $baz = new Foo\Bar\Baz(); // Includes 'classes/foo/bar/baz.php' * $baz = new foo\bar\Baz(); // Includes "classes/foo/bar/Baz.php"
* </code> * </code>
* *
* Multiple autoloaders can be registered at the same time: * To load classes within some namespace efficiently, directories can be
* assigned to a root namespace:
* <code> * <code>
* <code> * $loader = webbasics\Autoloader::getInstance();
* File structure: * $loader->addDirectory('models', 'models');
* classes/ *
* | foo.php // Contains class 'Foo' * // File "models/Foo.php"
* other_classes/ * namespace models;
* | bar.php // Contains class 'Bar' * class Foo extends ActiveRecord\Model { ... }
* </code> * </code>
* Autoloader::create('classes')->register(); *
* Autoloader::create('other_classes', true)->register(); * Exception throwing can be enabled in case a class does not exist:
* $foo = new Foo(); // Includes 'classes/foo.php' * <code>
* $bar = new Bar(); // Includes 'other_classes/bar.php', since 'classes/bar.php' does not exist * $loader = webbasics\Autoloader::getInstance();
* $baz = new Baz(); // Throws a FileNotFoundError, since 'other_classes/baz.php' does not exist * $loader->addDirectory('classes');
* $loader->setThrowExceptions(true);
*
* try {
* new Foo();
* } catch (webbasics\AutoloadError $e) {
* // "classes/Foo.php" does not exist
* }
* </code> * </code>
* *
* @package WebBasics * @package WebBasics
*/ */
class Autoloader extends Base { class Autoloader extends Base implements Singleton {
/** /**
* The root directory to look in. * Namespaces mapping to lists of directories.
* * @var array
* @var string
*/ */
private $root_directory; private $directories = array('\\' => array());
/** /**
* The namespace classes in the root directory are expected to be in. * Whether to throw an exception if a class file does not exist.
*
* This namespace is removed from the beginning of loaded class names.
*
* @var string
*/
private $root_namespace = '\\';
/**
* Whether to throw an exception when a class file does not exist.
*
* @var bool * @var bool
*/ */
private $throw_errors; private $throw_exceptions = false;
/** /**
* Create a new Autoloader instance. * @see Singleton::$instance
*
* @param string $root_directory Root directory of the autoloader.
* @param string $root_namespace Root namespace of classes loaded by the autoloader.
* @param bool $throw Whether to throw an exception when a class file does not exist.
*/ */
function __construct($root_directory, $root_namespace='\\', $throw=false) { private static $instance;
$this->setRootDirectory($root_directory);
$this->setRootNamespace($root_namespace);
$this->setThrowErrors($throw);
}
/** /**
* Set whether to throw an exception when a class file does not exist. * @see Singleton::getInstance()
*
* @param bool $throw Whether to throw exceptions.
*/ */
function setThrowErrors($throw) { static function getInstance() {
$this->throw_errors = !!$throw; if (self::$instance === null)
self::$instance = new self;
return self::$instance;
} }
/** /**
* Whether an exception is thrown when a class file does not exist. * Create a new Autoloader instance.
* *
* @return bool * Registers the {@link loadClass()} function to the SPL autoload stack.
*/ */
function getThrowErrors() { private function __construct() {
return $this->throw_errors; spl_autoload_register(array($this, 'loadClass'), true);
} }
/** /**
* Set the root directory from which classes are loaded. * Set whether to throw an exception when a class file does not exist.
* *
* @param string $directory The new root directory. * @param bool $throw Whether to throw exceptions.
*/ */
function setRootDirectory($directory) { function setThrowExceptions($throw) {
$this->root_directory = self::pathWithSlash($directory); $this->throw_exceptions = (bool)$throw;
} }
/** /**
* Get the root directory from which classes are loaded. * Whether an exception is thrown if a class file does not exist.
* *
* @return string * @return bool
*/ */
function getRootDirectory() { function getThrowExceptions() {
return $this->root_directory; return $this->throw_exceptions;
} }
/** /**
* Set the root namespace that loaded classes are expected to be in. * Add a new directory to look in while looking for a class within the given namespace.
*
* @param string $namespace The new root namespace.
*/ */
function setRootNamespace($namespace) { function addDirectory($directory, $namespace='\\') {
// Assert that the namespace ends with a backslash $directory = self::pathWithSlash($directory);
if ($namespace[strlen($namespace) - 1] != '\\')
$namespace .= '\\';
$this->root_namespace = $namespace; if ($namespace[0] != '\\')
} $namespace = '\\' . $namespace;
/** if (!isset($this->directories[$namespace]))
* Get the root namespace that loaded classes are expected to be in. $this->directories[$namespace] = array();
*
* @return string
*/
function getRootNamespace() {
return $this->root_namespace;
}
/** if (!in_array($directory, $this->directories[$namespace]))
* Convert a class name to a file name. $this->directories[$namespace][] = $directory;
*
* Uppercase letters are converted to lowercase and prepended
* by an underscore ('_').
*
* @param string $classname The class name to convert.
* @return string
*/
static function classnameToFilename($classname) {
return strtolower(preg_replace('/(?<=.)([A-Z])/', '_\\1', $classname));
} }
/** /**
* Strip the root namespace from the beginning of a class name. * Strip a namespace from the beginning of a class name.
* *
* @param string $namespace The namespace to strip.
* @param string $classname The name of the class to strip the namespace from. * @param string $classname The name of the class to strip the namespace from.
* @return string The stripped class name. * @return string The stripped class name.
*/ */
private function stripRootNamespace($classname) { private static function stripNamespace($namespace, $classname) {
$begin = substr($classname, 0, strlen($this->root_namespace)); if ($namespace != '\\')
$namespace .= '\\';
$begin = substr($classname, 0, strlen($namespace));
if ($begin == $this->root_namespace) if ($begin == $namespace)
$classname = substr($classname, strlen($this->root_namespace)); $classname = substr($classname, strlen($namespace));
return $classname; return $classname;
} }
...@@ -184,16 +159,14 @@ class Autoloader extends Base { ...@@ -184,16 +159,14 @@ class Autoloader extends Base {
* *
* @param string $classname The name of the class to create the file path of. * @param string $classname The name of the class to create the file path of.
*/ */
function createPath($classname) { private static function createPath($classname) {
$namespaces = array_filter(explode('\\', $classname)); $parts = array_filter(explode('\\', $classname));
$dirs = array_map('self::classnameToFilename', $namespaces); $path = '';
$path = $this->root_directory;
if (count($dirs) > 1) if (count($parts) > 1)
$path .= implode('/', array_slice($dirs, 0, count($dirs) - 1)).'/'; $path .= implode('/', array_slice($parts, 0, count($parts) - 1)) . '/';
$path .= end($dirs).'.php'; return $path . end($parts) . '.php';
return strtolower($path);
} }
/** /**
...@@ -203,33 +176,50 @@ class Autoloader extends Base { ...@@ -203,33 +176,50 @@ class Autoloader extends Base {
* namespace levels are used to indicate directory names. * namespace levels are used to indicate directory names.
* *
* @param string $classname The name of the class to load, including pepended namespace. * @param string $classname The name of the class to load, including pepended namespace.
* @param bool $throw Whether to throw an exception if the class file does not exist. * @return bool Whether the class file could be found.
* @return bool * @throws ClassNotFoundError If the class file does not exist.
* @throws FileNotFoundError If the class file does not exist. * @todo Unit test reverse-order namespace traversal
*/ */
function loadClass($classname, $throw=null) { function loadClass($classname) {
$classname = $this->stripRootNamespace($classname); // Prepend at least the root namespace
$path = $this->createPath($classname); if ($classname[0] != '\\')
$classname = '\\' . $classname;
// Find namespace directory
$parts = array_filter(explode('\\', $classname));
// Try larger namespaces first, getting smaller and smaller up to the global namespace
for ($i = count($parts); $i >= 0; $i--) {
$namespace = '\\' . implode('\\', array_slice($parts, 0, $i));
// If the namespace is mapped to a list of directories, attempt to
// load the class file from there
if (isset($this->directories[$namespace])) {
foreach ($this->directories[$namespace] as $directory) {
$class = self::stripNamespace($namespace, $classname);
$path = $directory . self::createPath($class);
if (file_exists($path)) {
require_once $path;
return true;
}
}
}
}
if (!file_exists($path)) { if ($this->throw_exceptions)
if ($throw || ($throw === null && $this->throw_errors)) throw new ClassNotFoundError($classname);
throw new FileNotFoundError($path);
return false; return false;
} }
}
require_once $path; /**
return true; * Exception, thrown when a class file could not be found.
}
/**
* Register the autoloader object to the SPL autoload stack.
*
* @param bool $prepend Whether to prepend the autoloader function to
* the stack, instead of appending it.
*/ */
function register($prepend=false) { class ClassNotFoundError extends FormattedException {
spl_autoload_register(array($this, 'loadClass'), true, $prepend); function __construct($classname) {
parent::__construct('could not load class "%s"', $classname);
} }
} }
......
...@@ -63,7 +63,7 @@ abstract class Base { ...@@ -63,7 +63,7 @@ abstract class Base {
* @return string * @return string
*/ */
static function pathWithSlash($directory) { static function pathWithSlash($directory) {
return $directory[strlen($directory) - 1] == '/' ? $directory : $directory.'/'; return $directory[strlen($directory) - 1] == '/' ? $directory : $directory . '/';
} }
} }
......
<?php <?php
require_once 'SingletonTestCase.php';
require_once 'autoloader.php'; require_once 'autoloader.php';
use webbasics\Autoloader; use webbasics\Autoloader;
define('PATH', 'tests/_files/'); define('PATH', 'tests/_files/');
class AutoloaderTest extends PHPUnit_Framework_TestCase { class AutoloaderTest extends SingletonTestCase {
function setUp() { function getClassName() {
$this->autoloader = new Autoloader(PATH); return 'webbasics\Autoloader';
} }
function testSetRootNamespace() { function tearDown() {
$this->assertAttributeEquals('\\', 'root_namespace', $this->autoloader); Autoloader::getInstance()->setThrowExceptions(false);
$this->autoloader->setRootNamespace('Foo');
$this->assertAttributeEquals('Foo\\', 'root_namespace', $this->autoloader);
$this->autoloader->setRootNamespace('Foo\\');
$this->assertAttributeEquals('Foo\\', 'root_namespace', $this->autoloader);
} }
/** function testStripNamespace() {
* @depends testSetRootNamespace $rmethod = new ReflectionMethod('webbasics\Autoloader', 'stripNamespace');
*/ $rmethod->setAccessible(true);
function testGetRootNamespace() { $this->assertEquals('Bar', $rmethod->invoke(null, 'foo', 'foo\Bar'));
$this->autoloader->setRootNamespace('Foo'); $this->assertEquals('Bar', $rmethod->invoke(null, '\foo', '\foo\Bar'));
$this->assertEquals($this->autoloader->getRootNamespace(), 'Foo\\');
} }
/** function testAddDirectory() {
* @depends testSetRootNamespace $autoloader = Autoloader::getInstance();
*/ $rprop = new ReflectionProperty($autoloader, 'directories');
function testConstructRootNamespace() { $rprop->setAccessible(true);
$autoloader = new Autoloader(PATH, 'Foo');
$this->assertAttributeEquals('Foo\\', 'root_namespace', $autoloader);
}
/** $autoloader->addDirectory(PATH);
* @depends testSetRootNamespace $this->assertEquals(array(
*/ '\\' => array(PATH)
function testStripRootNamespace() { ), $rprop->getValue($autoloader));
$strip = new ReflectionMethod('webbasics\Autoloader', 'stripRootNamespace');
$strip->setAccessible(true);
$this->autoloader->setRootNamespace('Foo'); $autoloader->addDirectory(PATH);
$this->assertEquals($strip->invoke($this->autoloader, 'Foo\Bar'), 'Bar'); $this->assertEquals(array(
} '\\' => array(PATH)
), $rprop->getValue($autoloader));
function testSetRootDirectory() { $autoloader->addDirectory('foo');
$this->autoloader->setRootDirectory('tests'); $this->assertEquals(array(
$this->assertEquals($this->autoloader->getRootDirectory(), 'tests/'); '\\' => array(PATH, 'foo/')
} ), $rprop->getValue($autoloader));
function testClassnameToFilename() { $autoloader->addDirectory('bar');
$this->assertEquals(Autoloader::classnameToFilename('Foo'), 'foo'); $this->assertEquals(array(
$this->assertEquals(Autoloader::classnameToFilename('FooBar'), 'foo_bar'); '\\' => array(PATH, 'foo/', 'bar/')
$this->assertEquals(Autoloader::classnameToFilename('fooBar'), 'foo_bar'); ), $rprop->getValue($autoloader));
$this->assertEquals(Autoloader::classnameToFilename('FooBarBaz'), 'foo_bar_baz');
$autoloader->addDirectory('foodir', 'foo');
$this->assertEquals(array(
'\\' => array(PATH, 'foo/', 'bar/'),
'\foo' => array('foodir/')
), $rprop->getValue($autoloader));
$autoloader->addDirectory('foobardir', 'foobar');
$this->assertEquals(array(
'\\' => array(PATH, 'foo/', 'bar/'),
'\foo' => array('foodir/'),
'\foobar' => array('foobardir/')
), $rprop->getValue($autoloader));
} }
/**
* @depends testClassnameToFilename
*/
function testCreatePath() { function testCreatePath() {
$this->assertEquals($this->autoloader->createPath('Foo'), PATH.'foo.php'); $rmethod = new ReflectionMethod('webbasics\Autoloader', 'createPath');
$this->assertEquals($this->autoloader->createPath('\Foo'), PATH.'foo.php'); $rmethod->setAccessible(true);
$this->assertEquals($this->autoloader->createPath('Foo\Bar'), PATH.'foo/bar.php'); $this->assertEquals($rmethod->invoke(null, 'Foo'), 'Foo.php');
$this->assertEquals($this->autoloader->createPath('Foo\Bar\Baz'), PATH.'foo/bar/baz.php'); $this->assertEquals($rmethod->invoke(null, '\Foo'), 'Foo.php');
$this->assertEquals($this->autoloader->createPath('FooBar\Baz'), PATH.'foo_bar/baz.php'); $this->assertEquals($rmethod->invoke(null, 'foo\Bar'), 'foo/Bar.php');
$this->assertEquals($rmethod->invoke(null, 'foo\Bar\Baz'), 'foo/Bar/Baz.php');
$this->assertEquals($rmethod->invoke(null, 'fooBar\Baz'), 'fooBar/Baz.php');
$this->assertEquals($rmethod->invoke(null, 'foo_bar\Baz'), 'foo_bar/Baz.php');
} }
function testThrowErrors() { function testThrowExceptions() {
$this->assertFalse($this->autoloader->getThrowErrors()); $autoloader = Autoloader::getInstance();
$this->autoloader->setThrowErrors(true); $this->assertFalse($autoloader->getThrowExceptions());
$this->assertTrue($this->autoloader->getThrowErrors()); $autoloader->setThrowExceptions(true);
$this->assertTrue($autoloader->getThrowExceptions());
} }
/** /**
* @depends testCreatePath * @depends testCreatePath
* @depends testThrowErrors * @depends testThrowExceptions
*/ */
function testLoadClassNotFound() { function testLoadClassNotFound() {
$this->assertFalse($this->autoloader->loadClass('foobar')); $this->assertFalse(Autoloader::getInstance()->loadClass('foobar'));
}
/**
* @depends testLoadClassNotFound
* @expectedException webbasics\FileNotFoundError
* @expectedExceptionMessage File "tests/_files/foobar.php" does not exist.
*/
function testLoadClassNotFoundError() {
$this->autoloader->setThrowErrors(true);
$this->autoloader->loadClass('foobar');
} }
/** /**
* @depends testLoadClassNotFound * @depends testLoadClassNotFound
* @expectedException webbasics\FileNotFoundError * @expectedException webbasics\ClassNotFoundError
* @expectedExceptionMessage File "tests/_files/foobar.php" does not exist.
*/ */
function testLoadClassNotFoundNoerrorOverwrite() { function testLoadClassNotFoundException() {
$this->autoloader->loadClass('foobar', true); $autoloader = Autoloader::getInstance();
$autoloader->setThrowExceptions(true);
$autoloader->loadClass('foobar');
} }
/** /**
* @depends testLoadClassNotFound * @depends testLoadClassNotFound
*/ */
function testLoadClassNotFoundErrorOverwrite() { function testLoadClassSuccess() {
$this->autoloader->setThrowErrors(true); $autoloader = Autoloader::getInstance();
$this->assertFalse($this->autoloader->loadClass('foobar', false)); $this->assertTrue($autoloader->loadClass('Foo'));
}
/**
* @depends testLoadClassNotFound
*/
function testLoadClass() {
$this->assertTrue($this->autoloader->loadClass('Foo'));
$this->assertTrue(class_exists('Foo', false)); $this->assertTrue(class_exists('Foo', false));
$this->assertTrue($this->autoloader->loadClass('Foo\Bar')); $this->assertTrue($autoloader->loadClass('Foo\Bar'));
$this->assertTrue(class_exists('Foo\Bar', false));
}
/**
* @depends testLoadClass
* @depends testStripRootNamespace
*/
function testLoadClassRootNamespace() {
$autoloader = new Autoloader(PATH.'foo');
$autoloader->setRootNamespace('Foo');
$this->assertTrue($autoloader->loadClass('Bar'));
$this->assertTrue(class_exists('Foo\Bar', false)); $this->assertTrue(class_exists('Foo\Bar', false));
} }
/**
* @depends testLoadClass
*/
function testRegister() {
$this->autoloader->register();
$this->assertTrue(class_exists('Baz'));
}
/**
* @depends testRegister
* @depends testThrowErrors
*/
function testRegisterPrepend() {
$second_loader = new Autoloader(PATH.'second');
$this->autoloader->register();
$second_loader->register(true); // Prepend so that the second loader attemps to load Bar first
$this->assertInstanceOf('Foo', new FooBaz());
}
} }
?> ?>
\ No newline at end of file
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment