4

I have followed the Symfony 4.3 docs to create a custom event, dispatch it, and listen for it. Tracing the execution of my controller, it looks like the event dispatcher does not find any subscribers, and I can't figure out what I'm doing wrong.

My event class is very basic:

namespace App\Event;

use Symfony\Contracts\EventDispatcher\Event;

class TestEvent extends Event
{
    public const NAME = 'test.event';

    protected $data;

    public function __construct(string $data)
    {
        $this->data = $data;
    }

    public function getData(): string
    {
        return $this->data;
    }
}

My controller instantiates and dispatches the event:

class TestController extends AbstractController
{
    private $eventDispatcher;

    public function __construct(EventDispatcherInterface $eventDispatcher, LoggerInterface $logger)
    {
        $this->eventDispatcher = $eventDispatcher;
    }

    /**
     * @Route("/event", name="event_test")
     */
    public function eventTest()
    {
        $event = new TestEvent('Event string');
        $this->eventDispatcher->dispatch($event);

        return $this->render('Test/TestEvent.html.twig', [
            'title' => 'Test Event',
            ]);
    }
}

I set up a subscriber to listen for the event and log. To make sure the subscriber works, I also subscribed to a Kernel event (that works):

namespace App\EventSubscriber;

use App\Event\TestEvent;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;

class TestSubscriber implements EventSubscriberInterface
{
    private $logger;

    public function __construct(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    public static function getSubscribedEvents()
    {
        return [
            TestEvent::NAME => [['onTestEvent', 20]],
            KernelEvents::REQUEST => 'onKernelRequest',
        ];
    }

    public function onTestEvent(TestEvent $event)
    {
        $this->logger->info('Subscriber says: Found test event');
        $this->logger->info('Subscriber says: Test event posted this data {data}', [
            'data' => $event->getData(),
        ]);
    }

    public function onKernelRequest()
    {
        $this->logger->info('Got Kernel Request');
    }
}

When I visit the /event URL, I see the expected output, and the logs show the Kernel request, but they don't show the test.event log.

Per the docs, I ran

php bin/console debug:event-dispatcher test.event

at the console and got

Registered Listeners for "test.event" Event


Order Callable Priority


#1 App\EventSubscriber\TestSubscriber::onTestEvent() 20


That tells me the subscriber is registered, but for some reason it is not being called. Any help would be fantastic!

(BTW, I tried with an event listener as well, and got the same results.)

Thanks!

2
  • Why does console show notify instead of onTestEvent?
    – Cerad
    Commented Aug 18, 2019 at 0:37
  • @Cerad Good catch, I changed the function name from "notify" to "onTestEvent" as I was composing this question. The console output I posted was old. I've updated the output.
    – Dan Meigs
    Commented Aug 18, 2019 at 1:35

1 Answer 1

12

In symfony 4.3 if you dispatch event like this $this->eventDispatcher->dispatch($event); dispather use method get_class($event) as event name, so in your subscriber you need change

TestEvent::NAME => [['onTestEvent', 20]],

to

TestEvent::class=> [['onTestEvent', 20]],

For listener use this:

App\Event\TestListener:
        tags:
            - { 'name': 'kernel.event_listener', 'event': 'App\Event\TestEvent', 'method': 'onTestEvent' }
6
  • Fascinating! That works like a charm, but to see the registered listener in the console I have to call it by class name (php bin/console debug:event-dispatcher "App\Event\TestEvent").
    – Dan Meigs
    Commented Aug 18, 2019 at 12:59
  • $dispatcher->dispatch($event, TestEvent::NAME); will make your original code work as well.
    – Cerad
    Commented Aug 18, 2019 at 15:06
  • Yes, but this is old way and soon be deprecated Commented Aug 18, 2019 at 15:28
  • Not exactly. The old way had you pass $eventName as the first argument. That approach has now been depreciated in 4.3. Passing $eventName as the second argument is now supported and will continue to be so. Notice that the various kernel events still use names like kernel.request even in 4.3. I don't disagree that you should use class name instead of event name but both approaches are fully supported and will continue to be so.
    – Cerad
    Commented Aug 19, 2019 at 12:45
  • For the record, dispatching with the event name in the second argument and subscribing to the name, as Cerad said, worked in my test as did dispatching without the name and subscribing to the class as @IhorKostrov said.
    – Dan Meigs
    Commented Aug 19, 2019 at 14:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.