14 Feb, 2009
Creating a custom View Helper in the Zend Framework
Posted by: Peter In: PHP| Zend Framework
Zend Framework ships with several View Helpers, such as the url View Helper. Anywhere in a view script one can call $this->url() to generate a url to a certain page. For example:
-
‘module’ => ‘moduleName’,
-
‘action’ => ‘actionName’,
-
‘additionalParam’ =>‘value’))
I wanted to create my own helper, for generating paths to thumbnails, and it turned out to be really simple. Since I wanted to be able to access the helper from any module, I created the view helper class in /library/My/View/Helper/Thumbnail.php. The definition of the class looks like this:
-
class My_View_Helper_Thumbnail extends Zend_View_Helper_Abstract
-
{
-
public function thumbnail($id, $type, $width, $height)
-
{
-
$thumbModel = new My_Model_Thumbnails();
-
return $thumbModel
-
->getThumbnail($id, $width, $height);
-
}
-
}
The getThumbnail() function will check if there exists a thumbnail (of size $width x $height) for the image with id $id, if one exists the path to it is returned. Otherwise the thumbnail will be generated on the fly.
The last piece of magic before it is possible to use our new view helper is to add one line to our bootstrap.php. After Zend MVC has been started, the path to our new view helper must be added to the layout in orders for view to be able to find it.
-
$layout = Zend_Layout::startMvc(APPLICATION_PATH . ‘/layouts/scripts’);
-
$layout->getView()->addHelperPath(‘My/View/Helper’, ‘My_View_Helper’);
When this is done it is possible to call $this->thumbnail() in all view scripts in the project.