Automate Symfony EventSubscriberInterface::getSubscribedEvents()
Martin Jirasek

Martin Jirasek @sirzarganwar

About: uhm, bio-logist?

Joined:
Dec 20, 2019

Automate Symfony EventSubscriberInterface::getSubscribedEvents()

Publish Date: Nov 25 '24
7 4

Do you like Symfony\Component\EventDispatcher\EventSubscriberInterface and it's getSubscribedEvents() method?

class AwesomeSubscriber implements Symfony\Component\EventDispatcher\EventSubscriberInterface
{

    public static function getSubscribedEvents(): array
    {
        return [
            HappyEvent::class => 'happy',
            CoolEvent::class => 'cool',
        ];
    }

    public function happy(HappyEvent $event): void {}

    public function cool(CoolEvent $event): void {}

}
Enter fullscreen mode Exit fullscreen mode

I hate it!

  1. Array with textual method name representation
  2. Event class-name written multiple times 😑

Yes, new Symfony has attribute #[AsEventListener], but what if you use another framework or older version of event-dispatcher or you don't like attributes?

There is simple solution 💥
See this trait https://github.com/Zarganwar/symfony-event-dispatcher-utils.
That provides you with a simple (automatic) way to subscribe to events to __invoke method.

class AwesomeSubscriber implements Symfony\Component\EventDispatcher\EventSubscriberInterface
{
    use AutoEventSubscriberTrait; // <<<--- This is it! ❤️

    public function __invoke(HappyEvent|CoolEvent $event): void {}

}
Enter fullscreen mode Exit fullscreen mode

or subscriber per event

class HappySubscriber implements Symfony\Component\EventDispatcher\EventSubscriberInterface
{
    use AutoEventSubscriberTrait;

    public function __invoke(HappyEvent $event): void {}

}

class CoolSubscriber implements Symfony\Component\EventDispatcher\EventSubscriberInterface
{
    use AutoEventSubscriberTrait;

    public function __invoke(CoolEvent $event): void {}

}
Enter fullscreen mode Exit fullscreen mode

Of course, you can use interfaces and union types.

Go to https://github.com/Zarganwar/symfony-event-dispatcher-utils and install

composer require zarganwar/symfony-event-dispatcher-utils

Enjoy! 🎉

Comments 4 total

  • Grégoire Pineau
    Grégoire PineauDec 1, 2024

    Hello. Why don't you use AsEventListener attribute ?

    • Martin Jirasek
      Martin JirasekDec 1, 2024

      Hi, the attribute is great, but when is event-dispatcher used in a different framework, it’s not as easy to implement. This is a simple alternative. But it is not bad idea, to use the Attribute inside too.

  • Christian
    ChristianDec 1, 2024

    What about the event priority?

    • Martin Jirasek
      Martin JirasekDec 1, 2024

      Yes, I was thinking about it, but it wasn’t essential for my use so far. It can be add it in the future. 👍

Add comment