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
--- a/templates/base.html.twig
+++ b/templates/base.html.twig
@@ -8,6 +8,15 @@
{% block javascripts %}{% endblock %}
</head>
<body>
+ <header>
+ <h1><a href="{{ path('homepage') }}">Guestbook</a></h1>
+ <ul>
+ {% for conference in conferences %}
+ <li><a href="{{ path('conference', { id: conference.id }) }}">{{ conference }}</a></li>
+ {% endfor %}
+ </ul>
+ <hr />
+ </header>
{% block body %}{% endblock %}
</body>
</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):
--- a/src/Controller/ConferenceController.php
+++ b/src/Controller/ConferenceController.php
@@ -29,12 +29,13 @@ class ConferenceController extends AbstractController
}
#[Route('/conference/{id}', name: 'conference')]
- public function show(Request $request, Conference $conference, CommentRepository $commentRepository): Response
+ public function show(Request $request, Conference $conference, CommentRepository $commentRepository, ConferenceRepository $conferenceRepository): Response
{
$offset = max(0, $request->query->getInt('offset', 0));
$paginator = $commentRepository->getCommentPaginator($conference, $offset);
return new Response($this->twig->render('conference/show.html.twig', [
+ 'conferences' => $conferenceRepository->findAll(),
'conference' => $conference,
'comments' => $paginator,
'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:
$ 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
--- a/src/EventSubscriber/TwigEventSubscriber.php
+++ b/src/EventSubscriber/TwigEventSubscriber.php
@@ -2,14 +2,25 @@
namespace App\EventSubscriber;
+use App\Repository\ConferenceRepository;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
+use Twig\Environment;
class TwigEventSubscriber implements EventSubscriberInterface
{
+ private $twig;
+ private $conferenceRepository;
+
+ public function __construct(Environment $twig, ConferenceRepository $conferenceRepository)
+ {
+ $this->twig = $twig;
+ $this->conferenceRepository = $conferenceRepository;
+ }
+
public function onControllerEvent(ControllerEvent $event)
{
- // ...
+ $this->twig->addGlobal('conferences', $this->conferenceRepository->findAll());
}
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
--- a/src/Repository/ConferenceRepository.php
+++ b/src/Repository/ConferenceRepository.php
@@ -19,6 +19,11 @@ class ConferenceRepository extends ServiceEntityRepository
parent::__construct($registry, Conference::class);
}
+ public function findAll()
+ {
+ return $this->findBy([], ['year' => 'ASC', 'city' => 'ASC']);
+ }
+
// /**
// * @return Conference[] Returns an array of Conference objects
// */
At the end of this step, the website should look like the following:
Going Further
- The Request-Response Flow in Symfony applications;
- The built-in Symfony HTTP events;
- The built-in Symfony Console events.
This work, including the code samples, is licensed under a Creative Commons BY-NC-SA 4.0 license.