Zend Framework View Helpers
Wednesday, October 7, 2009

The Zend Framework provides a convenient mechanism for encapsulating code used repeatedly to render parts of view scripts. For instance, it is shipped with the standard helper Zend_View_Helper_HtmlList, which is used to convert a list in PHP array for to the corresponding HTML markup. As well as the many standard helpers, it is also possible to create your own.

The mechanism for using view helpers is to first register the helper prefixes and locations; then you can simply run them from your script as member functions of the view object. For instance, you can invoke Zend_View_Helper_HtmlList like this from within your view script:

echo $this->htmlList($items, false, null, false);

Note that you should explicitly echo (or print) the variable returned by the helper for it to be displayed; by convention, a helper returns the markup it generates, rather than outputting it directly. This is to allow further processing of the result, should that be desired.

We have already seen an example of registering the helper prefixes and locations in my previous post Bootstrapping the Application: a Custom View Resource Plugin . There the resource plugin registered three sets of helpers: the standard helpers, the jQuery helpers and the application’s custom helpers.

We shall come back to the application’s custom view helpers in later posts. Next, however, are layouts.

Posted by James at 8:57 pm   0 comments

Leave a Reply