Creating an event subscriber
New to Drupal 8 is the event dispatcher system. One of the many benefits of Drupal is the ability to react to specific processes and alter or react to them. Unlike the hook system that exists in Drupal 8, and has for many versions of Drupal, the event dispatch system uses explicit registration to 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 REQUEST
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
interface:
<?php namespace Drupal\mymodule\EventSubscriber...