Step 12: Listening to Events

Listening to Events

The current layout is missing a navigation header to go back to the homepage or switch from one conference to the next.

Adding a Website Header

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

patch_file

  1. --- a/templates/base.html.twig
  2. +++ b/templates/base.html.twig
  3. @@ -8,6 +8,15 @@
  4. {% block javascripts %}{% endblock %}
  5. </head>
  6. <body>
  7. + <header>
  8. + <h1><a href="{{ path('homepage') }}">Guestbook</a></h1>
  9. + <ul>
  10. + {% for conference in conferences %}
  11. + <li><a href="{{ path('conference', { id: conference.id }) }}">{{ conference }}</a></li>
  12. + {% endfor %}
  13. + </ul>
  14. + <hr />
  15. + </header>
  16. {% block body %}{% endblock %}
  17. </body>
  18. </html>

Adding this code to the layout means that all templates extending it must define a conferences 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):

  1. --- a/src/Controller/ConferenceController.php
  2. +++ b/src/Controller/ConferenceController.php
  3. @@ -29,12 +29,13 @@ class ConferenceController extends AbstractController
  4. }
  5. #[Route('/conference/{id}', name: 'conference')]
  6. - public function show(Request $request, Conference $conference, CommentRepository $commentRepository): Response
  7. + public function show(Request $request, Conference $conference, CommentRepository $commentRepository, ConferenceRepository $conferenceRepository): Response
  8. {
  9. $offset = max(0, $request->query->getInt('offset', 0));
  10. $paginator = $commentRepository->getCommentPaginator($conference, $offset);
  11. return new Response($this->twig->render('conference/show.html.twig', [
  12. + 'conferences' => $conferenceRepository->findAll(),
  13. 'conference' => $conference,
  14. 'comments' => $paginator,
  15. 'previous' => $offset - CommentRepository::PAGINATOR_PER_PAGE,

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.

Discovering Symfony Events

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.

For instance, some events allow you to interact with the lifecycle of HTTP requests. During the handling of a request, the dispatcher dispatches events when a request has been created, when a controller is about to be executed, when a response is ready to be sent, or when an exception has been thrown. A listener can listen to one or more events and execute some logic based on the event context.

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.

Implementing a Subscriber

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

  1. $ symfony console make:subscriber TwigEventSubscriber

The command asks you about which event you want to listen to. Choose the Symfony\Component\HttpKernel\Event\ControllerEvent 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

  1. --- a/src/EventSubscriber/TwigEventSubscriber.php
  2. +++ b/src/EventSubscriber/TwigEventSubscriber.php
  3. @@ -2,14 +2,25 @@
  4. namespace App\EventSubscriber;
  5. +use App\Repository\ConferenceRepository;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  8. +use Twig\Environment;
  9. class TwigEventSubscriber implements EventSubscriberInterface
  10. {
  11. + private $twig;
  12. + private $conferenceRepository;
  13. +
  14. + public function __construct(Environment $twig, ConferenceRepository $conferenceRepository)
  15. + {
  16. + $this->twig = $twig;
  17. + $this->conferenceRepository = $conferenceRepository;
  18. + }
  19. +
  20. public function onControllerEvent(ControllerEvent $event)
  21. {
  22. - // ...
  23. + $this->twig->addGlobal('conferences', $this->conferenceRepository->findAll());
  24. }
  25. public static function getSubscribedEvents()

Now, you can add as many controllers as you want: the conferences variable will always be available in Twig.

Note

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

Sorting Conferences by Year and City

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

  1. --- a/src/Repository/ConferenceRepository.php
  2. +++ b/src/Repository/ConferenceRepository.php
  3. @@ -19,6 +19,11 @@ class ConferenceRepository extends ServiceEntityRepository
  4. parent::__construct($registry, Conference::class);
  5. }
  6. + public function findAll()
  7. + {
  8. + return $this->findBy([], ['year' => 'ASC', 'city' => 'ASC']);
  9. + }
  10. +
  11. // /**
  12. // * @return Conference[] Returns an array of Conference objects
  13. // */

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

Step 12: Listening to Events - 图1

Going Further


This work, including the code samples, is licensed under a Creative Commons BY-NC-SA 4.0 license.