Use PHP attributes for Event Subscriber wiring

Created on 31 January 2024, 5 months ago
Updated 1 February 2024, 5 months ago

Problem/Motivation

Reading through the related initiative "Use PHP attributes for Route Discovery" πŸ“Œ Use PHP attributes for route discovery Needs review , I felt that an even more helpful use of PHP Attributes would be in Event Subscriber wiring.

Currently, EventSubscribers get wired in a two-step process:

1. An entry in module.services.yml like so:

services:
...
  my_event_subscriber:
    class: Drupal\my\EventSubscriber\MyQueueSubscriber
    tags:
      -
        name: event_subscriber              

2. And, in your EventSubscriber class, implementing getSubscribedEvents() so Drupal knows which events this EventSubscriber subscribes to

  public static function getSubscribedEvents(): array {
    return [
      SomeEventClassEvents::EVENT_NAME => ['myCallback'],
      AnotherEventClassEvent::EVENT_NAME => ['myOtherCallback'],
    ];
  }

Taking my queue from the above linked issue, it seems we could accomplish both with one step, either like this:

#[SubscribedEvents(
  events: [
     SomeEventClassEvents::EVENT_NAME => 'myCallback'
     AnotherEventClassEvent::EVENT_NAME => 'myOtherCallback'
  ]
)]
class MyEventSubscriber implements EventSubscriberInterface {

or like this:

class MyEventSubscriber implements EventSubscriberInterface {


#[EventCallback([SomeEventClassEvents::EVENT_NAME])]
public function myCallback($event) {
}

#[EventCallback([AnotherEventClassEvents::EVENT_NAME])]
public function myOtherCallback($event) {
}

Two different ways of doing the exact same thing is a huge -- in my opinion, especially for people who are learning a framework.

User Longwave β†’ also pointed me to the fact that Symfony is using attributes for event discovery too. I might update the issue description to use their syntax.

Proposed resolution

1. Decide whether this is indeed an improvement and worth the effort.
2. Decide which format to use for wiring events this way.
3. Add the ability for core to wire events using the agreed-upon format.
4. Deprecate event subscription wiring using services.yml and EventSubscriberInterface::getSubscribedEvents()

✨ Feature request
Status

Active

Version

11.0 πŸ”₯

Component
OtherΒ  β†’

Last updated less than a minute ago

Created by

πŸ‡ΊπŸ‡ΈUnited States apotek

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Production build 0.69.0 2024