symfonyeventssyliussylius-resource

Is there a way, within my handler method, to determine which of the subscribed events triggered the handler?


Assuming I have an EventListener tagged with more than one named event, or an EventSubscriber that subscribes to more than one event, how can I, within my handler method, determine which of the subscribed events triggered the handler?

In sylius, all the resource events use (a descendant of ) the Generic Event class.

I can see that the event name is not contained within the event class, so how can i establish which of the subscribed events caused the handler to run ?

    public static function getSubscribedEvents()
    {
        return [
            'sylius.order.post_complete' => 'dispatchMessage',
            'sylius.customer.post_register' => 'dispatchMessage',
        ];
    }

UPDATE: I am aware that in this instance i could call get_class($event->getSubject()) and at least know which resource i'm dealing with, I am however looking for a more generic solution that would work in any symfony project.


Solution

  • There are more parameters passed to the callbacks than just the event object (you might come across them by calling func_get_args() inside your callback (dispatchMessage) quicker than in the documentation :-)). They're not mandatory but they contain what you might need.

    The callback gets called with, as parameters :
    - event (the object)
    - event name (what you're looking for)
    - dispatcher instance

    (see https://github.com/symfony/event-dispatcher/blob/master/EventDispatcher.php#L231)

    So in your case you can use the following :

    public static function getSubscribedEvents()
    {
        return [
            'sylius.order.post_complete' => 'dispatchMessage',
            'sylius.customer.post_register' => 'dispatchMessage',
        ];
    }
    
    public function dispatchMessage(GenericEvent $event, string $eventName, EventDispatcherInterface $eventListener)
    {
        // Here, $eventName will be 'sylius.order.post_complete' or 'sylius.customer.post_register'
    }