Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
PHP 5.4 Namespace-based Autoloader
<?php
// Probably unnecessary, but wanted to test the waters of 5.4
trait NamespaceConverter
{
function nsToPath($class) {
return str_replace('\\', DIRECTORY_SEPARATOR, $class) . '.php';
}
}
// Namespace-based paths (e.g. "new Foo\Component\Bar()" => "/Foo/Component/Bar.php")
class Autoloader
{
use NamespaceConverter;
public $basePath;
public function __construct($basePath = '.')
{
$this->basePath = realpath($basePath);
spl_autoload_register([$this, 'load']);
}
public function load($class)
{
$file = $this->basePath . DIRECTORY_SEPARATOR . $this->nsToPath($class);
if (file_exists($file)) include $file;
}
}
/*
Usage:
$loader1 = new Autoloader('path/to/some/core/classes');
$loader2 = new Autoloader('path/to/some/vendor/classes');
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment