Skip to content

Instantly share code, notes, and snippets.

@reyramos
Last active August 29, 2015 14:04
Show Gist options
  • Select an option

  • Save reyramos/349fcd24034d16173401 to your computer and use it in GitHub Desktop.

Select an option

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]
<?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