AsEventListener
This module allows developers to register event listeners in Drupal using Symfony's #[AsEventListener] attribute. This provides a more streamlined way to subscribe to and react to events within your Drupal site, similar to how it's done in Symfony. It offers an alternative to the traditional Drupal service tagging method.
The "AsEventListener" module enables developers to use the Symfony attribute #[AsEventListener] to register event subscribers/listeners.
To register an event subscriber in Drupal you need to create a service and tag
it as event_subscriber. See Subscribe to and dispatch events on drupal.org.
Symfony however defines the attribute #[AsEventListener] so developers are able to register classes or single methods as event listeners. This module brings this feature to Drupal.
It is planned to add this feature to Drupal core. Until #3376163 is fixed, this module provides a way to make use of it now.
Usage
To make use of this module you need to setup classes or methods as event
listeners using #[AsEventListener]. The classes needs to be in namespace Drupal\[...]\EventListener to be registered automatically.
Example
<?php
namespace Drupal\my_custom_module\EventListener;
#[AsEventListener(event: RoutingEvents::ALTER)]
class TestEventListener {
/**
* Use the class directly as event listener.
*
* @param \Drupal\Core\Routing\RouteBuildEvent $event
* The dispatched event.
*/
public function __invoke(RouteBuildEvent $event): void {
// Do something.
}
}
This will add this class as event listener for RoutingEvents::ALTER so every time this event is dispatched, TestEventListener::__invoke() is called.
See Defining Event Listeners with PHP Attributes for details about how to use #[AsEventListener].