Events Reference for ZF2 Applications

One of the most powerful aspects of a Zend Framework 2 application is the event manager. Right out of the box a skeleton application has impressive features which can be added to or replaced using events. Events also make it possible to write modules that can interact with the application while keeping its own code completely separate.

The downside to events is that they add a layer of abstraction that makes it more difficult to understand and trouble shoot an application. To write new event listeners or trouble shoot existing ones you need to understand how they all work together, but it is difficult to even know what listeners are attached to which events. As your application becomes more complicated it becomes more difficult to keep track of how all the pieces fit together.

To help myself keep track of event listeners in my applications I wrote a view helper that can inspect an Event Manager object and render a list of events and their corresponding listeners. You can see it in action with this live demo of events reference. This alone is helpful to understand the basic structure of a ZF2 application, but to take full advantage of the helper you’ll want to be able to use it in your own application. Lucky for you I added it to the Spork Tools module and you find the source code on GitHub.

To use the view helper all you need to do is pass an event manager object to it as a parameter. Keep in mind this could reveal security sensitive information so you should make sure this is not publicly accessable.

// controller action
public function indexAction()
    return array(
        'events' => $this->getApplication()->getEventManager(),

// view script
echo $this->sporkToolsEvents($events);

Leave a Reply

Your email address will not be published. Required fields are marked *