I have an application that executes docker containers in async mode using a messenger (DemoExecution). Hence, the user can launch an execution of the container without waiting its end. We need to know when the container has ended and delivered its results, so we can tell the user and also refresh the result output. So I’m trying (without success) to dispatch an event from a MessageHandler.
I’ve created an Event (DemoEvent) and a Subscriber (DemoSubscriber). Then I tried to dispatch the event from MessageHandler (DemoExecutionHandler) but it doesn’t work. However, I did exactely the same call (See the code below) from a Controller and then the event is listened correctly. I can’t find a way to send the event at the end of the MessageHandler, to mention that the container has finished its execution.
So I wonder if it’s possible to dispatch an event from other things than a Controller (I didn’t manage to find the answer) ? If not what could you advise ?
Thanks for your help.
<?php
namespace AppEvent;
use SymfonyContractsEventDispatcherEvent;
class DemoEvent extends Event
{
const NAME = 'DemoExecutionEvent';
protected $content;
public function __construct(string $content)
{
$this->content = $content;
}
public function setContent(string $content): void
{
$this->content = $content;
}
public function getContent(): string
{
return $this->content;
}
}
<?php
namespace AppEventSubscriber;
use SymfonyComponentEventDispatcherEventSubscriberInterface;
use PsrLogLoggerInterface;
use TwigEnvironment;
use AppEventDemoEvent;
class DemoSubscriber implements EventSubscriberInterface
{
public function __construct(private readonly LoggerInterface $logger, private Environment $twig)
{
}
public function onDemoExecutionEvent(DemoEvent $demoEvent): void
{
$this->logger->info(__METHOD__);
$this->logger->info($demoEvent::NAME);
$this->logger->info($demoEvent->getContent());
}
/**
* @return []
*/
public static function getSubscribedEvents()
{
return [
// Defines which event to listen On doit définir une priorité élevée
DemoEvent::class => [['onDemoExecutionEvent', 200]],
];
}
}
The code in a Controller sends the Event which listened by the subscriber
$eventDispatcher->dispatch(new DemoEvent('DemoEvent is sent from Controller.'));
The code in a MessageHandler doesn’t seem to send the Event and is not listened by the subscriber
$eventDispatcher->dispatch(new DemoEvent('DemoEvent is sent from handler'));
daquarius is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.