phpsymfonysymfony4symfony-eventdispatcher

How I can fire publish method once the event is fired?


I have the following event class definition:

use Symfony\Contracts\EventDispatcher\Event;

class CaseEvent extends Event
{
    public const NAME = 'case.event';

    // ...
}

And I have created a subscriber as follow:

use App\Event\CaseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class CaseEventListener implements EventSubscriberInterface
{
    public static function getSubscribedEvents(): array
    {
        return [CaseEvent::NAME => 'publish'];
    }

    public function publish(CaseEvent $event): void
    {
        // do something
    }
}

I have also defined the following at services.yaml:

App\EventSubscriber\CaseEventListener:
  tags:
    - { name: kernel.event_listener, event: case.event}

Why when I dispatch such event as follow the listener method publish() is never executed?

/**
 * Added here for visibility but is initialized in the class constructor
 *
 * @var EventDispatcherInterface
 */
private $eventDispatcher;

$this->eventDispatcher->dispatch(new CaseEvent($args));

I suspect the problem is kernel.event_listener but not sure in how to subscribe the listener to the event properly.


Solution

  • Change your subscriber so getSubscribedEvents() reads like this:

    public static function getSubscribedEvents(): array
    {
        return [CaseEvent::class => 'publish'];
    }
    

    This takes advantage of changes on 4.3; where you no longer need to specify the event name, and makes for the simpler dispatching you are using (dispatching the event object by itself, and omitting the event name).

    You could have also left your subscriber as it was; and change the dispatch call to the “old style”:

    $this->eventDispatcher->dispatch(new CaseEvent($args), CaseEvent::NAME);
    

    Also, remove the event_listener tags from services.yaml. Since you are implementing EventSubscriberInterface, you do not need to add any other configuration.