$npx -y skills add edutrul/drupal-ai --skill drupal-eventsDrupal event subscribers — Symfony events (PSR-14), KernelEvents, services.yml tags, and hooks vs events decision guide.
| 1 | # Drupal Event Subscribers |
| 2 | |
| 3 | ## Example (Best Practice) |
| 4 | |
| 5 | ```php |
| 6 | // src/EventSubscriber/MyEventSubscriber.php |
| 7 | namespace Drupal\my_module\EventSubscriber; |
| 8 | |
| 9 | use Drupal\Core\Session\AccountProxyInterface; |
| 10 | use Symfony\Component\EventDispatcher\EventSubscriberInterface; |
| 11 | use Symfony\Component\HttpKernel\Event\RequestEvent; |
| 12 | use Symfony\Component\HttpKernel\KernelEvents; |
| 13 | |
| 14 | final class MyEventSubscriber implements EventSubscriberInterface { |
| 15 | |
| 16 | public function __construct( |
| 17 | private readonly AccountProxyInterface $currentUser, |
| 18 | ) {} |
| 19 | |
| 20 | public static function getSubscribedEvents(): array { |
| 21 | return [ |
| 22 | // Note: Higher priority runs earlier. Default is 0. |
| 23 | KernelEvents::REQUEST => ['onRequest', 100], |
| 24 | ]; |
| 25 | } |
| 26 | |
| 27 | public function onRequest(RequestEvent $event): void { |
| 28 | if (!$event->isMainRequest()) { |
| 29 | return; |
| 30 | } |
| 31 | |
| 32 | if (!$this->currentUser->isAuthenticated()) { |
| 33 | return; |
| 34 | } |
| 35 | |
| 36 | // Example: log or modify behavior for authenticated users. |
| 37 | } |
| 38 | |
| 39 | } |
| 40 | ``` |
| 41 | |
| 42 | ## Register in services.yml |
| 43 | |
| 44 | ```yaml |
| 45 | services: |
| 46 | my_module.my_event_subscriber: |
| 47 | class: Drupal\my_module\EventSubscriber\MyEventSubscriber |
| 48 | arguments: ['@current_user'] |
| 49 | tags: |
| 50 | - { name: event_subscriber } |
| 51 | ``` |
| 52 | |
| 53 | ## Common Events |
| 54 | |
| 55 | | Event | Constant | When | |
| 56 | |---|---|---| |
| 57 | | Request | `KernelEvents::REQUEST` | Every request | |
| 58 | | Response | `KernelEvents::RESPONSE` | Before response sent | |
| 59 | | Terminate | `KernelEvents::TERMINATE` | After response sent | |
| 60 | | Exception | `KernelEvents::EXCEPTION` | On uncaught exception | |
| 61 | |
| 62 | ## Generate with Drush |
| 63 | |
| 64 | ```bash |
| 65 | drush generate event-subscriber --answers='{ |
| 66 | "module": "my_module", |
| 67 | "class": "MyEventSubscriber", |
| 68 | "event": "kernel.request" |
| 69 | }' |
| 70 | ``` |