A free and open-source book on Zend Framework for beginners


3.7. Events & Application's Life Cycle

As you've learned from the previous section, on every HTTP request, the Zend\Mvc\Application object is created. Typically, an application "lives" for a second or less (this time is enough to generate the HTTP response). The application's "life" consists of several stages.

Zend Framework 3 uses the concept of event. 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.

Each application life stage is initiated by the application by triggering an event (this event is represented by the MvcEvent class living in Zend\Mvc namespace). Other classes (either belonging to Zend Framework or specific to your application) may listen to events and react accordingly.

Below, the five main events (life stages) are presented:

Bootstrap. When this event is triggered by the application, a module has a chance to register itself as a listener of further application events in its onBootstrap() callback method.

Route. When this event is triggered, the request's URL is analyzed using a router class (typically, with Zend\Router\Http\TreeRouteStack class). If an exact match between the URL and a route is found, the request is passed to the site-specific controller class assigned to the route.

Dispatch. The controller class "dispatches" the request using the corresponding action method and produces the data that can be displayed on the web page.

Render. On this event, the data produced by the controller's action method are passed for rendering to Zend\View\Renderer\PhpRenderer class. The renderer class uses a view template file for producing an HTML page.

Finish. On this event, the HTTP response is sent back to client.

The event flow is illustrated in figure 3.3:

Figure 3.3. Event flow during the application's life cycle Figure 3.3. Event flow during the application's life cycle

Although needed relatively rarely, some practical examples of how to listen and react to an event can be found in Creating a New Module chapter.


Top