Hooks in Action Helpers

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:

<?php

class Zend_Controller_Action_Helper_Quote extends Zend_Controller_Action_Helper_Abstract
{
    function preDispatch()
    {
        $view $this->getActionController()->view;
        $view->footerQuote $this->getQuote();
    }
    
    
    function 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(0count($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
    Zend_Controller_Action_HelperBroker::addPath(
        APPLICATION_PATH .'/controllers/helpers');
        
    $hooks Zend_Controller_Action_HelperBroker::getStaticHelper('Quote');
    Zend_Controller_Action_HelperBroker::addHelper($hooks);

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:

<div id="footer">
    <div id="quote">
        <?php echo $this->footerQuote?> 
    </div> 
</div>

That's it - not too hard, is it?

Zip Files:
I've updated the example project from the last post so you can see it in context.

If you would like to comment on this article, please ping me on twitter.
If your response won't fit into 140 characters, write a blog post and then ping me!