Last active
August 29, 2015 14:04
-
-
Save reyramos/349fcd24034d16173401 to your computer and use it in GitHub Desktop.
PHP autoloader script, using SPL_AUTOLOAD_REGISTER.Just set the $dir, path relative from the autoloader file, optional exclude array for files not to include in the autoloader.It will include all files with namespace, others will be ignored.namespace follow PSR-0 standard, If using phpunit * phpunit --bootstrap autoload.php [testFile]
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 | |
| /** | |
| * | |
| * PHP autoloader script, using SPL_AUTOLOAD_REGISTER. | |
| * It will include all files with namespace, others will be ignored. | |
| * | |
| * namespace follow PSR-0 standard | |
| * | |
| * If using phpunit | |
| * phpunit --bootstrap autoload.php [testFile] | |
| * | |
| * @param $dir , path relative from the autoloader file, | |
| * @param $exclude , optional files not to include in the autoloader | |
| * | |
| */ | |
| $dir = 'classes'; | |
| $exclude = array(); //files to exclude | |
| spl_autoload_register( | |
| function ($class) { | |
| static $classes = null; | |
| if ($classes === null) { | |
| $path = __DIR__ . "/".$GLOBALS['dir']."/"; | |
| $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), FilesystemIterator::KEY_AS_PATHNAME); | |
| $classes = array(); | |
| foreach ($objects as $file => $object) { | |
| $f = str_replace($path, '', $file); | |
| if (!in_array(str_replace('/','',substr($f, strripos($f, '/'))), array_merge($GLOBALS['exclude'], array(".", "..", substr(__FILE__, (strrpos(__FILE__, '/') + 1)))))) { | |
| $str = file_get_contents(__DIR__ . '/' . $GLOBALS['dir'] . '/' . $f); | |
| preg_match("/namespace\\s(.*?);/", $str, $matches); | |
| if (array_key_exists(1, $matches)){ | |
| $classes = array_merge($classes, array(strtolower($matches[1]) . '\\' .strtolower(str_replace(array('/','.php'),'',substr($f, strripos($f, '/')))) => '/' . $GLOBALS['dir'] . '/' . $f)); | |
| } | |
| } | |
| } | |
| } | |
| $cn = strtolower($class); | |
| if (isset($classes[$cn])) { | |
| require __DIR__ . $classes[$cn]; | |
| } | |
| } | |
| ); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment