Created
November 10, 2012 22:17
-
-
Save ScreamingDev/4052737 to your computer and use it in GitHub Desktop.
PHP PSR-0 Autoload (with Phar)
This file contains 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
/** | |
* Enhanced PSR-0 autoloader with Phar-Support | |
* | |
* @param $class string Name of the class (with namespace) | |
* | |
* @author Ralf Mike Pretzlaw <kontakt@mike-pretzlaw.de> | |
* @copyright 2012 Ralf Mike Pretzlaw | |
* | |
* @throws Exception | |
*/ | |
function autoloadPSR ( $class ) | |
{ | |
/** | |
* PSR-0 | |
* https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md | |
*/ | |
$className = ltrim($class, '\\'); | |
$fileName = ''; | |
$namespace = ''; | |
if ( $lastNsPos = strripos($className, '\\') ) | |
{ | |
$namespace = substr($className, 0, $lastNsPos); | |
$className = substr($className, $lastNsPos + 1); | |
$fileName = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR; | |
} | |
$fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php'; | |
/** | |
* PHAR-Part | |
*/ | |
$pharFile = Phar::running() . DIRECTORY_SEPARATOR . $fileName; | |
if ( false !== stream_resolve_include_path($fileName) ) | |
{ // exists in at least one include-path: require it | |
require_once $fileName; | |
} | |
else if ( file_exists($pharFile) ) | |
{ // is in phar archive: require the phar file | |
require_once $pharFile; | |
} | |
else | |
{ // neither phar nor in include-path: that's bad | |
throw new \Exception( 'File with definition of ' . $class . ' could not be found.' ); | |
} | |
if ( false == class_exists($class, false) && false == interface_exists($class, false) ) | |
{ // class doesn't exists after including a file: bad too | |
throw new \Exception( 'Definition for ' . $class . ' not found.' ); | |
} | |
} | |
spl_autoload_register('autoloadPSR', true, true); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment