Search code examples
phpnamespacespearautoloaderpsr-0

PHP: Autoloading PEAR namespaced classes within PSR-0 namespaced classes conflict


For my application I am using PSR-0 namespaces. Everything works beautiful!

Until I wanted to use Twig as template parser, Twig uses PEAR pseudo namespaces. Like Twig_Loader_Filesystem.

The problem is that when I want to use Twig inside my name-spaced application like this:

<?php
namespace Tact\ViewManager;

class ViewManager {

    public function init()
    {
        $loader = new Twig_Loader_Filesystem($this->templatepath);
        $this->twig = new Twig_Environment($loader);
    }  
}
?>

PHP will tell my autoloader to look for an class named Tact\ViewManager\Twig_Loader_Filesystem

How can I manage to autoload PEAR name-spaced style classes without the PSR-0 namespace of the invoking class?

My autoloader is able to load both PEAR and PSR-0..

Thanks in advance!


Solution

  • This is because you are in the Tact\ViewManager namespace. The pseudo-namespaced classes are in fact in the global namespace, so you should prefix them with \ to call them:

    $loader = new \Twig_Loader_Filesystem($this->templatepath);
    

    If the \ prefix bugs you, you could do this:

    namespace Tact\ViewManager;
    
    use Twig_Loader_Filesystem;
    use Twig_Environment;
    
    class ViewManager {
        public function init()
        {
            $loader = new Twig_Loader_Filesystem($this->templatepath);
            $this->twig = new Twig_Environment($loader);
        }  
    }