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!