I'm using a service with an autowired dispatcher to dispatch an event. In order to test events, I've added an event subscriber just before dispatching the event. However, the registered subscriber isn't logging the method I would expect it to do.
The event:
<?php
namespace App\Event;
use Symfony\Component\EventDispatcher\Event;
class GameStartEvent extends Event {
}
The subscriber:
<?php
namespace App\Event;
use Psr\Log\LoggerAwareTrait;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class GameStartSubscriber implements EventSubscriberInterface {
use LoggerAwareTrait;
public function __construct(LoggerInterface $logger) {
$this->setLogger($logger);
}
public static function getSubscribedEvents() {
return [
"game.started" => [
[
'logEvent',
],
]
];
}
public function logEvent(GameStartEvent $event): void {
$this->logger->info("the game has started");
}
}
And this is the used service that is supposed to dispatch events the event registration is supposed to happen somewhere else in the future. I just did it here for testing:
<?php
namespace App\Service;
use App\Event\GameStartEvent;
use App\Event\GameStartSubscriber;
use Psr\Log\LoggerInterface;
use Psr\SimpleCache\CacheInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
class GameCacheService {
private $eventDispatcher;
private $logger;
public function __construct(EventDispatcherInterface $eventDispatcher, LoggerInterface $logger) {
$this->eventDispatcher = $eventDispatcher;
$this->logger = $logger;
}
// some other methods...
function startGame() {
// some code...
$gameStartSubscriber = new GameStartSubscriber($this->logger);
$this->eventDispatcher->addSubscriber($gameStartSubscriber);
$this->eventDispatcher->dispatch("game.started", new GameStartEvent());
}
}
After calling the service method, the specified logger message isn't written down.
You seem to have at least your Event in App/Entity which is not autowired by default and shouldn't be. Have a look at your services.yml, it should be excluded from Autowiring. Move your stuff to something like App/Event
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With