Understanding the stack index for Zend Framework Controller plugins

Zend Framework Controller plugins are a powerful way to inject logic into your controller system at various points, such as before and after an action dispatch. Plugins are run in the order they are added, though it is possible to change the order by defining a custom stack index. ZF internal plugins such as Zend_Controller_Plugin_ErrorHandler, which displays a nice Error 404 page, has a stack index of 100 to ensure it runs near the end of any plugin cycle. However, it’s not so obvious from the ZF manual how to set a custom stack index.

For example, you may have a common admin system layout that does various things to your admin page layout before the page is displayed. This could be registered in your controller as so:

$front = $this->getFrontController();
$adminLayout = new My_Controller_Plugin_AdminLayout($this->_helper->layout());
$front->registerPlugin($adminLayout);

If you want to alter the plugin so it runs after any other local plugins you could specify a stack index of 10 as a second argument:

$front->registerPlugin($adminLayout, 10);

However, unless you know what the existing plugin stack indexes are it’s difficult to know what stack index you should be using. You can use this small code snippet to output the plugin name and its associated stack index, again via your controller.

foreach ($front->getPlugins() as $stackIndex => $plugin) {
    Zend_Debug::dump(get_class($plugin), $stackIndex);
}

The standard ZF plugin list should be something like:

99 string(36) "Zend_Layout_Controller_Plugin_Layout"
100 string(35) "Zend_Controller_Plugin_ErrorHandler"
999 string(33) "Zend_Wildfire_Channel_HttpHeaders"

Hope this helps shed light on a rather useful feature of ZF! You can find out more at this excellent Devzone article on Front Controller Plugins in Zend Framework.

4 Replies to “Understanding the stack index for Zend Framework Controller plugins”

  1. Hello,
    a good hint, just a little editorial inconsistency, you write in text those lines, which don’t match:

    ‘Zend_Controller_Plugin_ErrorHandler, which displays a nice Error 404 page, has a stack index of 999’

    ‘100 string(35) “Zend_Controller_Plugin_ErrorHandler”‘

Comments are closed.