PHP - most lightweight psr-0 compliant autoloader

后端 未结 7 838
猫巷女王i
猫巷女王i 2020-12-01 09:55

I have a tiny application that i need an autoloader for. I could easily use the symfony2 class loader but it seems like overkill.

Is there a stable extremely lightw

7条回答
  •  爱一瞬间的悲伤
    2020-12-01 10:16

    The PSR-0 specification document has an examplary compatible autoloader function that is already pretty short:

    function autoload($className)
    {
        $className = ltrim($className, '\\');
        $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';
    
        require $fileName;
    }
    

    It's usage is pretty straight forward:

    spl_autoload_register('autoload');
    

    The shortcoming with it is, that you need to configure base-directories it works on with the include_path directive. To support a hybrid PSR-0 autoloaders leaned onto SPL semantics, the following one supportss include path and spl autoload extensions:

    $spl_autoload_register_psr0 = function ($extensions = null) 
    {
        $callback = function ($className, $extensions = null) 
        {
            if (!preg_match('~^[a-z0-9\\_]{2,}$~i', $className)) {
                return;
            }
            null !== $extensions || $extensions = spl_autoload_extensions();
            $extensions = array_map('trim', explode(',', $extensions));
            $dirs = array_map('realpath', explode(PATH_SEPARATOR, get_include_path()));
    
            $classStub = strtr($className, array('_' => '/', '\\' => '/'));
    
            foreach ($dirs as $dir) {
                foreach ($extensions as $extension) {
                    $file = sprintf('%s/%s%s', $dir, $classStub, $extension);
                    if (!is_readable($file)) {
                        continue;
                    }
                    include $file;
                    return;
                }
            }
        };
    
        return spl_autoload_register($callback);
    };
    

    The The Symfony2 ClassLoader Component has the benefit to allow more configuration here. You can install it easily via Pear or Composer (symfony/class-loader on Packagist). It is a component on it's own that is used by many and fairly well tested and supported.

提交回复
热议问题