Step 12: Listening to Events

Listening to Events

Anything that should be displayed on all web pages, like a header, should be part of the main base layout:

patch_file

Adding this code to the layout means that all templates extending it must define a variable, which must be created and passed from their controllers.

As we only have two controllers, you might do the following (do not apply the change to your code as we will learn a better way very soon):

Imagine having to update dozens of controllers. And doing the same on all new ones. This is not very practical. There must be a better way.

Twig has the notion of global variables. A global variable is available in all rendered templates. You can define them in a configuration file, but it only works for static values. To add all conferences as a Twig global variable, we are going to create a listener.

Symfony comes built-in with an Event Dispatcher Component. A dispatcher dispatches certain events at specific times that listeners can listen to. Listeners are hooks into the framework internals.

Events are well-defined extension points that make the framework more generic and extensible. Many Symfony Components like Security, Messenger, Workflow, or Mailer use them extensively.

Another built-in example of events and listeners in action is the lifecycle of a command: you can create a listener to execute code before any command is run.

Any package or bundle can also dispatch their own events to make their code extensible.

To avoid having a configuration file that describes which events a listener wants to listen to, create a subscriber. A subscriber is a listener with a static getSubscribedEvents() method that returns its configuration. This allows subscribers to be registered in the Symfony dispatcher automatically.

You know the song by heart now, use the maker bundle to generate a subscriber:

The command asks you about which event you want to listen to. Choose the event, which is dispatched just before the controller is called. It is the best time to inject the conferences global variable so that Twig will have access to it when the controller will render the template. Update your subscriber as follows:

patch_file

Note

We will talk about a much better alternative performance-wise in a later step.

Ordering the conference list by year may facilitate browsing. We could create a custom method to retrieve and sort all conferences, but instead, we are going to override the default implementation of the findAll() method to be sure that sorting applies everywhere:

patch_file

At the end of this step, the website should look like the following:

Going Further