Micchaleq
Micchaleq

Reputation: 433

Symfony5 Listen custom event in bundle

all

I would like to Listen an event in the custom bundle. I know that the problem is wiring an event because when I use it in the main path it works. My code is simple:

Firstly I have an event class like BeforeCrudActionEvent which has some default felds/methods. Secodly I create instance of my event class and dispatch it using EventDispatcherInterface like that:

$event = new BeforeCrudActionEvent();
$this->get('event_dispatcher')->dispatch($event);

The name of event is not defined and it is generated automatically (consists namespace and name of the class).

Lastly I created Subscriber class which implements EventSubscriberInterface

class TestSubscriber implements EventSubscriberInterface
{

    public static function getSubscribedEvents()
    {
        return [
            BeforeCrudActionEvent::class => ['updateList']
        ];
    }

    public function updateList(BeforeCrudActionEvent $event)
    {
        throw new \Exception("It's works");
    }
}

As I wrote before when the Subscriber class is in the main directory it works, but when it is in the custom bundle it doesn't. Im sure that it have to be added to service.yaml file but I can't find this configuration in the documentation. Which tag and which event (if required) schould I use?

Upvotes: 0

Views: 81

Answers (1)

GrenierJ
GrenierJ

Reputation: 1140

at the end of the paragraph in doc, it's write :

You can also manually add the kernel.event_subscriber tag.

So you need to register your eventSubscriber has a service and add the tag "kernel.event_subscriber".

NameSpace\TestSubscriber:
    tags:
        - { name: kernel.event_subscriber }

After that you could check that your subscriber is configured with the call to php bin/console debug:event-dispatcher "event.name"

Upvotes: 1

Related Questions