Creating an event subscriber to react to events
Drupal has two ways of integrating various parts of the system: using hooks or events. Hooks have been a part of Drupal for its entire lifespan and events were introduced in Drupal 8. Unlike the hook system, which has implicit registration, the event dispatch system uses explicit registration for an event.
The events dispatcher system comes from the Symfony framework and allows components to easily interact with one another. Within Drupal, and integrated Symfony components, events are dispatched, and event subscribers can listen to the events and react to changes or other processes.
In this recipe, we will subscribe to the RequestEvent
event, which fires when a request is first handled. If the user is not logged in, we will navigate them to the login page.
How to do it…
- Create
src/EventSubscriber/RequestSubscriber.php
in your module. - Define the
RequestSubscriber
class, which implements theEventSubscriberInterface...