Skip to content

Instantly share code, notes, and snippets.

@codedmonkey
Last active August 29, 2015 14:00
Show Gist options
  • Save codedmonkey/11071505 to your computer and use it in GitHub Desktop.
Save codedmonkey/11071505 to your computer and use it in GitHub Desktop.
Simple PSR-4 autoloader
<?php
/**
* Very simple PSR-4 compatible autoloader
*/
function __autoload($className)
{
/**
* Specify Directories
*
* Example:
*
* 'Acme\\Foo\\' => 'src/acme/foo/src/'
*
* would look for the class `Acme\Foo\Bar` in the file:
*
* src/acme/foo/src/Bar.php
*/
$directories = array(
'CodedMonkey\\Sample\\' => 'src/sample/src/',
);
foreach ($directories as $namespace => $directory) {
// Check if the called class is part of this namespace
if (strpos($className, $namespace) !== 0) {
continue;
}
// Strip the namespace from the class name (Enables PSR-4)
$className = str_replace($namespace, '', $className);
// Build the path to the supposed class file
$className = str_replace('\\', '/', $className);
$filename = rtrim($directory, '/') . '/' . $className . '.php';
if (!file_exists($filename)) {
continue;
}
include_once $filename;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment