Skip to content

Instantly share code, notes, and snippets.

@hakre
Created December 26, 2013 17:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hakre/8136464 to your computer and use it in GitHub Desktop.
Save hakre/8136464 to your computer and use it in GitHub Desktop.
spl_autoload_register() just with added PSR-0 support
<?php
/**
* spl_autoload_register() just with added PSR-0 support
*
* The support is added, that means, for each classname first of all
* by the priority given in the include-path directive, a per-directory
* test is done for the full-classname based file and then sub-directories
* are traversed.
*
* PHP 5.3 Namespace Separators are always mapped to a directory to
* prevent different behavior on file-systems that are supporting the
* backslash "\" like windows.
*
* @link http://www.php.net/manual/en/function.spl-autoload.php
*
* @param null $extensions
*
* @return bool
*/
$spl_autoload_register_psr0 = function ($extensions = null) {
$callback = function ($className, $extensions = null) {
if (!preg_match('(^(?:\\\\?[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)+$)', $className)) {
return;
}
null !== $extensions || $extensions = spl_autoload_extensions();
$includePath = get_include_path();
$extensions = array_map('trim', explode(',', $extensions));
$dirs = array_map('realpath', explode(PATH_SEPARATOR, $includePath));
$includes = array();
$classStubNewNs = strtr($className, '\\', '/');
$classStubOldNs = strtr($classStubNewNs, '_', '/');
foreach ($dirs as $dir) {
foreach ($extensions as $extension) {
$includes[] = sprintf('%s/%s%s', $dir, $classStubNewNs, $extension);
$includes[] = sprintf('%s/%s%s', $dir, $classStubOldNs, $extension);
}
}
foreach ($includes as $file) {
if (!is_readable($file)) {
continue;
}
include $file;
}
};
return spl_autoload_register($callback);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment