Home >Backend Development >PHP Tutorial >Automate Symfony\\Component\\EventDispatcher\\EventSubscriberInterface::getSubscribedEvents() with simple Trait

Automate Symfony\\Component\\EventDispatcher\\EventSubscriberInterface::getSubscribedEvents() with simple Trait

Patricia Arquette
Patricia ArquetteOriginal
2024-11-27 18:10:11310browse

Automate Symfony\Component\EventDispatcher\EventSubscriberInterface::getSubscribedEvents() with simple Trait

Do you like SymfonyComponentEventDispatcherEventSubscriberInterface and it's getSubscribedEvents() method?

class AwesomeSubscriber implements Symfony\Component\EventDispatcher\EventSubscriberInterface
{

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

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

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

}

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|AnotherEvent $event): void {}

}

or SRP 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 {}

}

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! ?

The above is the detailed content of Automate Symfony\\Component\\EventDispatcher\\EventSubscriberInterface::getSubscribedEvents() with simple Trait. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn