1

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!

mmmmm
  • 595
  • 2
  • 5
  • 20

2 Answers2

2

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);
    }  
}
igorw
  • 27,759
  • 5
  • 78
  • 90
Ivan Pintar
  • 1,861
  • 1
  • 15
  • 27
  • Thanks for your reply! I already tried that but than my autoloader will detect the `\` prefix and tries to include it the PSR-0 way.. I am afraid your solution is the only solution to get things working.. – mmmmm Sep 12 '12 at 11:01
  • Quote: "I am afraid your solution is the only solution to get things working", did it work or not? What do you mean by "including it the PSR-0" way. Where does it look for the class? Could you edit the post to show the autoloader code (the bit where you transform the namespaces into directories)? – Ivan Pintar Sep 12 '12 at 11:03
  • Sorry, you were right. It works! But as I said before. It looks really ugly :P – mmmmm Sep 12 '12 at 11:10
  • Nice solution! Did not even think of that. U made my day:) – mmmmm Sep 12 '12 at 11:23
  • @igorw corrupted your answer to be not functional – mmmmm Sep 12 '12 at 14:48
  • @WoutvanderVegt Sorry about that, fixed now. – igorw Sep 12 '12 at 15:08
0

Try this:

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

This will tell PHP to force namespace\class lookup at "root" level, and if your autoloader is setup to load both namespaces and regular PEAR convention classnames it will work.

Ivan Hušnjak
  • 3,493
  • 3
  • 20
  • 30
  • My autoloader indeed gets the class name without the namespace prefix. So things can work now. But it looks so damn ugly.. Thanks! – mmmmm Sep 12 '12 at 11:07