Last active
August 29, 2015 14:00
-
-
Save codedmonkey/11071505 to your computer and use it in GitHub Desktop.
Simple PSR-4 autoloader
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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