Php Symfony事件订阅者没有';不要对派遣作出反应
我正在使用一个带有自动连线调度程序的服务来调度事件。为了测试事件,我在发送事件之前添加了一个事件订阅者。但是,注册的订阅者并没有像我期望的那样记录方法 活动:Php Symfony事件订阅者没有';不要对派遣作出反应,php,symfony,events,listener,Php,Symfony,Events,Listener,我正在使用一个带有自动连线调度程序的服务来调度事件。为了测试事件,我在发送事件之前添加了一个事件订阅者。但是,注册的订阅者并没有像我期望的那样记录方法 活动: <?php namespace App\Event; use Symfony\Component\EventDispatcher\Event; class GameStartEvent extends Event { } 代替 `$this->eventDispatcher->dispatch(“game.started
<?php
namespace App\Event;
use Symfony\Component\EventDispatcher\Event;
class GameStartEvent extends Event {
}
代替
`$this->eventDispatcher->dispatch(“game.started”,new GameStartEvent())`
具有
`$this->eventDispatcher->dispatch(“game.started”,$event)`
您似乎至少在App/Entity
中有您的事件,默认情况下它不是自动连接的,不应该是自动连接的。查看一下你的services.yml,它应该被排除在自动连线之外。将您的资料移动到类似于App/Event
的位置,服务方法中不存在$Event
变量。而且我很确定变量不是问题所在。如果是这样的话,我可能会得到某种异常,说明我没有为logEvent
方法提供正确的参数。啊,是的,对不起,这个答案完全是胡说八道。我测试了你的代码,它对我有效。您知道是调度程序、事件还是记录器不工作吗?您似乎还有事件名称空间App\Entity
。你确定那是对的?
<?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());
}
}