A free and open-source book on ZF3 for beginners

3.12. About Event Manager

In this section, we will give some advanced information about event manager. You can relatively safely skip this section, however refer to it if you plan to implement some advanced event listeners in your website.

Previously in this chapter we have mentioned that the application life cycle consists of events. One class can trigger an event, and other classes may listen to events. Technically, triggering an event means just calling another class' "callback" method. The event management is implemented inside of the Zend\EventManager component.

ZF3 (and particularly its Zend\Mvc component) hardly depends on events to operate, and because of that its source code is a combination of event listeners which is rather difficult to understand. Fortunately, in most cases you do not need to understand how ZF3 triggers and handles events internally, you just need to understand what event is, what events present in application life cycle and what is the difference between usual event manager and shared event manager.

3.12.1. Event & MvcEvent

An event is technically an instance of the Zend\EventManager\Event class. An event can basically have at least the following parts:

It is possible to create custom types of events by extending the Event class. For example, the Zend\Mvc component defines the custom event type named Zend\Mvc\MvcEvent, which extends the Event class and adds several properties and methods needed for the Zend\Mvc component to work.

3.12.2. EventManager & SharedEventManager

It is important to understand the difference between the usual event manager and the shared event manager.

The usual event manager is not stored as a singleton in the service manager. Every time you request the EventManager service from the service manager, you receive a new instance of it. This is done for privacy and performance reasons:

But, in case if someone intentionally needs to listen to other's events, there is a special shared event manager. The SharedEventManager service is stored in the service manager as a singleton, so you can be sure everyone will have the same instance of it.

With the SharedEventManager, you can attach a listener to private events triggered by certain class (or several classes). You specify the unique class identifier(s) to which you would like to listen. That simple!

Some practical examples of how to listen and react to an event can be found in Creating a New Module chapter and User Management, Authentication & Access Filtering chapter.