Following on from the discussion on Zend Framework Action Helpers, let's talk about hooks within them.
Hooks are a feature of action helpers that allow you to automatically run code at certain points in the dispatch cycle. Specially, there are two hook functions available for action helpers:
- preDispatch(): runs before the action function is called
- postDispatch(): runs after the action function has completed
These allow you to ensure that some functionality is always run for each request. Let's consider a simple example of displaying a random quote in the footer of a website.
We start with an action helper in our controllers/helpers directory called Quote:
class Zend_Controller_Action_Helper_Quote extends Zend_Controller_Action_Helper_Abstract
$view = $this->getActionController()->view;
$view->footerQuote = $this->getQuote();
$quotes = 'I want to run, I want to hide, I want to tear down the walls';
$quotes = 'One man come in the name of love, One man come and go';
return $quotes[rand(0, count($quotes)-1)];
The preDispatch() method, collects the view from the action controller and then assigns a random quote to the footerQuote property.
We need to tell the helper broker that we want this helper's hooks to be run, so in addition to the addHelperPath() call, our bootstrap requires a call to addHelper(). The bootstrap therefore has this code within it:
// Action Helpers
$hooks = Zend_Controller_Action_HelperBroker::getStaticHelper('Quote');
As we used addPath() to tell the helper broker where to find the action helpers, we can use getStaticHelper() as an easy way to instantiate the class without having to require() and then call new. We can then register it with the helper broker using addHelper().
As the quote is displayed in the footer, the HTML required lives in layout.phtml:
<?php echo $this->footerQuote; ?>
That's it - not too hard, is it?
I've updated the example project from the last post so you can see it in context.