Using another helper inside a view helper

PHP

Since I keep noticing that some people do not know how to call or use another helper from within a view helper, here is a short example.

It is important to derive your own class from Zend_View_Helper_Abstract. This matters because the base class provides the "view" property and the setView() method. The method is important because it is populated through "setter injection." This means the function automatically receives the view inside the "_getPlugin" method in the Zend_View class. So you no longer have to worry about passing the view in. It really could not be simpler.

But how do I now get to my other view helper? That is very simple now. View helpers can be called directly through a view object, since internally the corresponding helper is called via __call().

Example of a helper:

require_once 'Zend/View/Helper/Abstract.php'  
  
class MyModule_View_Helper_MyHelper extends Zend_View_Helper\_Abstract  
{  
    public function myHelper()  
    {  
        return $this->view->partial('myfile.phtml', array('foo' => 'bar'));  
    }  
}  

What happens here? The view has already been passed in and can therefore be used internally. The "view" property holds the object. The partial helper is instantiated directly through the view object. Internally, Zend_View uses the PluginLoader and loads the corresponding helper as needed. But we do not need to care about that. We only need to extend the right base class.