Events, the EventManager and ListenerAggregates in Zend Framework 2

There are a bunch of good articles on this subject on the web already, but for my own reference I put together this article listing the steps to take to set up your own custom event listeners in your ZF2 application. Start by creating a class handling the events. This class will implement the Zend\EventManager\ListenerAggregateInterface. In this example I will create a listener aggregate that takes care of sending out e-mails for different events. I like to keep my listener aggregates to be groupings of related actions in response to events. For example I would have a LogEventsListener listening to the ‘runtime_error’ event. The handler for this event would for instance make a log entry of what went wrong. At the same time I would have a MailEventsListener also listening to the ‘runtime_error’ event and send out an e-mail to the developer or administrator when a fatal error occurs in the application (random example). Besides the ‘runtime_error’ event there could be other events that either the LogEventsListener or MailEventsListener deal with. So back to the code the MailEventsListener could look like this. MyApp\Listener\MailEventsListener.php:   <?php namespace MyApp\Listener; use Zend\EventManager\EventInterface; use Zend\EventManager\EventManagerInterface; use Zend\EventManager\ListenerAggregateInterface; use Zend\ServiceManager\ServiceLocatorAwareTrait; use Zend\ServiceManager\ServiceLocatorAwareInterface; use MyApp\Config\ConfigAwareTrait; use ...

(Read more...)