Instead provided callback function you can also provide static method:
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpKernel\KernelEvents;
class MyService
{
public function __construct(private EventDispatcherInterface $eventDispatcher)
{
$this->eventDispatcher = $eventDispatcher;
}
public function createJob($query)
{
//...
//createThingOnApi() method must be static
$this->eventDispatcher->addListener(KernelEvents::TERMINATE, [self::class, 'createThingOnApi']);
}
public static function createThingOnApi()
{
//...
}
}
Source: https://jfoucher.com/2017/08/symfony-process-custom-events-in-kernel-terminate.html
But using static method did not meet my needs because I needed many dependent services. so I saved event in Request object and processed it using Subscriber that runs on KernelEvents::TERMINATE
event.
1.
//put this line in Service
/** @var Symfony\Component\HttpFoundation\RequestStack $request*/
$request->attributes->add([
'user' => $newUserEvent
]);
Usage of Request Attributes
- then my KernelEvents::TERMINATE Subscriber:
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\TerminateEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class PostResponseSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return [
KernelEvents::TERMINATE => 'doPostResponseProcesses',
];
}
public function doPostResponseProcesses(TerminateEvent $event): void
{
$request = $event->getRequest();
$userEvent = $request->attributes->get('user');
if (!$userEvent) {
return;
}
//process event ...
}
}