In Symfony application, we can create and dispatch custom events. Events dispatching is useful when wanted to keep different application components separated from each other.
This tutorial provides 2 methods how to dispatch event in Symfony 7 application.
Method 1 - event object
Register an event listener or subscriber that listens on the specified event by the fully-qualified class name (FQCN). Pass just the event object to the dispatch
method to notify all listeners and subscribers of the given event.
<?php
namespace App\Controller;
use App\Event\MessageSentEvent;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
class TestController
{
#[Route('/')]
public function index(EventDispatcherInterface $dispatcher): Response
{
$dispatcher->addListener(MessageSentEvent::class, function (MessageSentEvent $evt) {
echo $evt->getMessage();
});
$evt = new MessageSentEvent('Hello world');
$dispatcher->dispatch($evt);
return new Response();
}
}
<?php
namespace App\Event;
use Symfony\Contracts\EventDispatcher\Event;
class MessageSentEvent extends Event
{
public function __construct(private string $message) {}
public function getMessage(): string { return $this->message; }
}
Method 2 - event object and event name
Register an event listener or subscriber that listens on the specified event by its name. Pass the event object and event name to the dispatch
method to notify all listeners and subscribers of the given event.
<?php
namespace App\Controller;
use App\Event\MessageSentEvent;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
class TestController
{
#[Route('/')]
public function index(EventDispatcherInterface $dispatcher): Response
{
$dispatcher->addListener(MessageSentEvent::NAME, function (MessageSentEvent $evt) {
echo $evt->getMessage();
});
$evt = new MessageSentEvent('Hello world');
$dispatcher->dispatch($evt, MessageSentEvent::NAME);
return new Response();
}
}
<?php
namespace App\Event;
use Symfony\Contracts\EventDispatcher\Event;
class MessageSentEvent extends Event
{
public const NAME = 'message.sent';
public function __construct(private string $message) {}
public function getMessage(): string { return $this->message; }
}
Leave a Comment
Cancel reply