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
ZF3 (and particularly its
Zend\Mvccomponent) 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.
An event is technically an instance of the
An event can basically have at least the following parts:
It is possible to create custom types of events by extending the
For example, the
Zend\Mvc component defines the custom event type named
which extends the
Event class and adds several properties and methods
needed for the
Zend\Mvc component to work.
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
service from the service manager, you receive a new instance of it. This is done for privacy and performance reasons:
It is assumed by default that the class triggering events will request and save somewhere its own private event manager, because it doesn't want other classes to automatically listen to those events. Events triggered by the class are assumed to belong to that class privately.
If anyone would be able to listen to any event triggered by any class, there would be performance hell - too many event listeners would be invoked, thus increasing page load time. It is better to avoid this by keeping events private.
But, in case if someone intentionally needs to listen to other's events, there is a special shared event manager. The
service is stored in the service manager as a singleton, so you can be sure everyone will have the same instance of it.
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.