Search code examples
phppearautoloadpsr-0

Can PSR-0 class autoloader, load PEAR library?


So this is my question, I wrote my own class autoloader that fallows PSR-0 standard. That's easy. Now I have my PHP MVC Frameowrk and I would like to use Twig, but Twig fallows PEAR naming standard that use _ instead of \.

Now is it true that PSR-0 Autoloaders should also be able to load PEAR libs? Since inside those Autoloaders _ is transformed into \? My loader can't load Twig if I register it, but it may be I made a mistake somewhere.

Should PSR-0 compatible class loader be able to load PEAR libs too?


Solution

  • PSR-0 should be able to work with both full-qualified namespaces and underscored classes. All you should need to do is replace the underscores with a directory seperator. A good example would be:

    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;
    }
    

    Hope this helps!