我正在使用带有自动接线调度程序的服务来调度事件.为了测试事件,我在调度事件之前添加了一个事件订阅者.但是,注册订户没有记录我希望它执行的方法.
事件:
<?php
namespace App\Event;
use Symfony\Component\EventDispatcher\Event;
class GameStartEvent extends Event {
}
订户:
<?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");
}
}
这是使用过的服务,用于分派事件,而事件注册应该在将来的其他地方发生.我只是在这里做测试:
<?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());
}
}
调用服务方法后,不会记录指定的记录器消息.
解决方法:
更换
$this-> eventDispatcher-> dispatch(“ game.started”,new GameStartEvent());`
与
$this-> eventDispatcher-> dispatch(“ game.started”,$event);`
您似乎在App / Entity中至少拥有您的事件,该事件默认情况下不会自动关联,因此不应该自动关联.看一下您的services.yml,应该将其排除在自动装配之外.将您的东西移动到类似App / Event的地方