Sorry, you need to enable JavaScript to visit this website.
Skip to main content
Welcome to our website! Explore our services and portfolio.

Creating an Event Subscriber in Drupal

Submitted by admin on

  It should: implement interface EventSubscriberInterface

  - pass dependencies:

EntityTypeManagerInterface $entity_type_manager,
AdminContext $admin_context,
DateFormatterInterface $date_formatter,
RequestStack $request_stack


In the services.yml:

arguments: [ '@entity_type.manager', '@router.admin_context', '@date.formatter', '@request_stack' ]
tags:
- { name: event_subscriber }



  - implement getSubscribedEvents in the interface

     - e.g. $events[ NodePreprocessEvent::name('article')] = ['articlePreprocessEvent']; with use Drupal\preprocess_event_dispatcher\Event\NodePreprocessEvent;
    - e.g. $events[KernelEvents::REQUEST][] = ['onRequest', 100]; with use Symfony\Component\HttpKernel\Event\RequestEvent;



 

In Drupal, an Event Subscriber is the modern equivalent of the old "hook" system.1 It allows your module to listen for specific actions—like a kernel request, a configuration change, or a user login—and react to them.2

 

To create one, you need to follow these three steps:


1. Register the Service

First, you must tell Drupal that your class exists and that it should be tagged as an event_subscriber. 3Add this to your module's my_module.services.yml file.

 

YAML

services:
  my_module.event_subscriber:
    class: Drupal\my_module\EventSubscriber\MyExampleSubscriber
    tags:
      - { name: event_subscriber }

2. Create the Subscriber Class

Create the PHP file at src/EventSubscriber/MyExampleSubscriber.php.

The class must implement Symfony\Component\EventDispatcher\EventSubscriberInterface. This interface requires a getSubscribedEvents() method, which maps Events to Methods within your class.

PHP

namespace Drupal\my_module\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\RequestEvent;

/**
 * Custom Event Subscriber for my_module.
 */
class MyExampleSubscriber implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    // List the events you want to listen to and the method to call.
    return [
      KernelEvents::REQUEST => [['onKernelRequest', 0]],
    ];
  }

  /**
   * This method is called whenever the KernelEvents::REQUEST event is fired.
   *
   * @param \Symfony\Component\HttpKernel\Event\RequestEvent $event
   * The event object.
   */
  public function onKernelRequest(RequestEvent $event) {
    $request = $event->getRequest();
    // Do something with the request, like checking headers or redirecting.
  }
}

3. Clear Cache

Because you added a new service in a .yml file, Drupal won't recognize it until you clear the cache:4

drush cr


Common Event Types

Depending on what you want to achieve, you will likely use one of these common event sources:

  • Kernel Events (KernelEvents): REQUEST, TERMINATE, EXCEPTION, VIEW.

  • Config Events (ConfigEvents): SAVE, DELETE, RENAME.

  • Routing Events (RoutingEvents): ALTER (Used for dynamically changing route permissions or paths).

  • Entity Events: (Note: For standard CRUD operations like "node save," Drupal still largely uses Hooks or Entity Bundle Classes, though some contrib modules provide event wrappers).

How to Find Available Events

Since Drupal is built on Symfony, many events are standard.5 To see all events currently registered in your specific Drupal site, you can use Drush:

drush devel:event (Requires the Devel module)

Would you like an example of how to subscribe to a specific event, such as a Redirect on a 404 error or responding to a Config change?