【问题标题】:Symfony event subscriber doesn't react to dispatchSymfony 事件订阅者对调度没有反应
【发布时间】:2019-01-28 09:42:42
【问题描述】:

我正在使用带有自动装配调度程序的服务来调度事件。为了测试事件,我在调度事件之前添加了一个事件订阅者。但是,注册的订阅者并没有按照我期望的方式记录它。

事件:

<?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());   
    }
}

调用服务方法后,指定的记录器消息没有写下来。

【问题讨论】:

    标签: php symfony events listener


    【解决方案1】:
    代替 `$this->eventDispatcher->dispatch("game.started", new GameStartEvent());` 和 `$this->eventDispatcher->dispatch("game.started", $event);`

    您似乎至少在App/Entity 中有您的事件,默认情况下不自动连接,也不应该自动连接。看看你的 services.yml,它应该被排除在自动装配之外。将您的内容移至App/Event

    【讨论】:

    • 服务方法中不存在$event 变量。另外我很确定变量不是问题。如果是这种情况,我可能会得到某种异常,说明我没有为 logEvent 方法提供正确的参数。
    • 啊,是的,对不起,这个答案完全是废话。我测试了你的代码,它对我有用。您知道是调度程序、事件还是记录器不工作?此外,您似乎拥有 Event 命名空间 App\Entity。你确定这是正确的?
    猜你喜欢
    • 2018-02-02
    • 2018-02-19
    • 2020-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-16
    相关资源
    最近更新 更多