Zend_View: Access the view from a view helper

It's in the manual, but I thought I'd blog about my simple View Helper setup that ensures that I can get at the view with minimal effort.

Firstly we create a parent class:

<?php

abstract class My_View_Helper_Abstract
{
    protected $_view;
    
    public function setView($view)
    {
        $this->_view $view;
    }
}

This class contains the code required by Zend_View to collect an instance of the view and assign it to a protected variable. All my view helpers extend this class and so I can acess the view using $this->_view. For instance:

<?php

require_once 'My/View/Helper/Abstract.php';

class My_View_Helper_TreeUl extends My_View_Helper_Abstract
{
    /**
     * Render a nested array as a set of nested <ul>s.
     *
     * @param array|instanceof Iterator $list
     * @return string
     */
    function treeUl($list)
    {
        $output ";
        if (is_array($list) || $list instanceof Iterator) {
            if (count($list) > 0) {
                $output "<ul>\n";
                foreach ($list as $item) {
                    $output .= "\t<li>";
                    if(is_string($item)) {
                        $output .= $this->_view->escape($item);
                    } else {
                        $output .= $this->treeUl($item);
                    }
                    $output .= "</li>\n";
                }
                $output .= "</ul>\n";
            }
        }
        return $output;
    }
}

Simple, isn't it ?!

4 Responses to “Zend_View: Access the view from a view helper”

  1. 1 Harro

    You need to add an extra slash for the \\n and \\t, they are getting escaped out ;)

  2. 2 Rob...

    The joy of Wordpress :)

    Thanks!

    Regards,

    Rob…

  3. 3 Mary

    When would you want to use this technique? I mean, what does it do? I realize this is painfully noob of me (realize that I am new to programming… sorry) but I don't see what this buys me.

  4. 4 Rob...

    Mary,

    Generally, you use this when you need to access other view helpers. In the example, I needed access to the escape() view helper from within another one.

    The easiest way is to wrap up the boring bit into a parent class and then it's available whenever you need it without any extra work.

    Does that make sense?

    Regards,

    Rob…

The views expressed in these comments are not the views of the publisher. However, we believe in the rights of others to express their legitimate views and concerns. Any legitimate complaint emailed to rob@akrabat.com will be seriously considered and the post reviewed as desirable and necessary.

Leave a Reply

Pre order