Skip to content

Instantly share code, notes, and snippets.

@brianium
Created March 12, 2012 18:54
Show Gist options
  • Save brianium/2023954 to your computer and use it in GitHub Desktop.
Save brianium/2023954 to your computer and use it in GitHub Desktop.
PHP 5 Autoloader with Namespace support
<?php
class Autoloader
{
protected $directory;
protected $methodQueue;
/**
* @param string $dir the directory to look from
*/
public function __construct($dir) {
if(is_dir($dir)) {
$this->directory = $dir;
} else {
require_once 'Exception.php';
throw new AutoloadException("Autoloader directory does not exist");
}
$this->methodQueue = new \SplQueue();
}
/**
* @param string $cls the class that could not be found
*/
public function includeClass($cls) {
$file = str_replace("\\",DIRECTORY_SEPARATOR,$cls);
$path = $this->directory . DIRECTORY_SEPARATOR . $file . '.php';
if (file_exists($path)) {
require_once $path;
}
}
/**
* Add a method to the queue. All methods in the queue will
* be executed before the default includeClass method is registered
* @param $cb a callback to be executed
*/
public function addMethod($cb) {
$this->methodQueue->enqueue($cb);
}
public function register() {
$this->methodQueue->rewind();
while($this->methodQueue->current()) {
call_user_func($this->methodQueue->dequeue());
}
spl_autoload_register(array($this,'includeClass'));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment