
If you’re working with Drupal 9, 10, or Drupal 11, you’ve probably heard about Event Subscribers. These are powerful tools that let you “listen” to what’s happening inside Drupal and react to those events.
What is an Event Subscriber in Drupal?
In this article, we’ll go over what an event subscriber is, why you’d use one, and how to create a custom event subscriber cleanly and simply.
An event subscriber is a PHP class that listens for specific events and performs some action when those events occur. For example, when a user logs in or when a node is saved, you can “catch” that event and do something, like logging a message or sending an email.
How to Create a Custom Event Subscriber in Drupal?
Let’s build a simple event subscriber that logs a message when a user logs in.
Step 1: Create a Custom Module
/modules/custom/custom_events
├── custom_events.info.yml
└── custom_events.services.yml
custom_events.info.yml
name: 'Custom Events'
type: module
description: 'Provides custom event subscribers.'
core_version_requirement: ^10 || ^11
package: Custom
version: 1.0
Step 2: Define the Event Subscriber Service
Create the file: custom_events.services.yml
services:
custom_events.user_login_subscriber:
class: Drupal\custom_events\EventSubscriber\UserLoginSubscriber
arguments: ['@logger.factory']
tags:
- { name: event_subscriber }
Step 3: Create the Subscriber Class
Now create the folder and file:
/modules/custom/custom_events/src/EventSubscriber/UserLoginSubscriber.php
UserLoginSubscriber.php
<?php
namespace Drupal\custom_events\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\EventDispatcher\Event;
use Drupal\user\Event\UserEvents;
use Drupal\user\Event\UserLoginEvent;
use Psr\Log\LoggerInterface;
class UserLoginSubscriber implements EventSubscriberInterface {
protected $logger;
public function __construct(LoggerInterface $logger_factory) {
$this->logger = $logger_factory->get('custom_events');
}
public static function getSubscribedEvents() {
return [
UserEvents::LOGIN => 'onUserLogin',
];
}
public function onUserLogin(UserLoginEvent $event) {
$account = $event->getAccount();
$this->logger->info('User @name just logged in.', ['@name' => $account->getAccountName()]);
}
}
Clear Cache and Test
Enable your module using drush
drush en custom_eventsClear the cache and you should see a message like:
The user admin just logged in.
Event subscribers in Drupal are a clean and modern way to add your own logic to core or contributed events. You don’t need to hack or override anything — just listen and act.

0 Comments