我创建了一些新事件,如 app.client_enter
或 app.client_leave
. 现在我想注册一个监听器来监听这个事件 . 如果我在同一个命令中添加一个监听器,它就可以工作了 .
ClientListener.php
namespace AppBundle\Service;
use AppBundle\Event\ClientEnterEvent;
class ClientListener {
public function onClientEnter(ClientEnterEvent $event) {
echo "It could be working";
}
}
service.yml(更新)
services:
app.client_listener:
class: AppBundle\Service\ClientListener
tags:
- { name: kernel.event_listener, event: app.client_enter, method: onClientEnter }
ClientCommand.php
namespace AppBundle\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;
use AppBundle\Event\ClientEnterEvent;
class ClientCommand extends ContainerAwareCommand {
protected function configure() { ... }
protected function execute(InputInterface $input, OutputInterface $output) {
$dispatcher = new EventDispatcher();
$dispatcher->dispatch('app.client_enter', new ClientEnterEvent("Maxi"));
}
3 回答
谢谢你们 . 我找到了解决方案,在ContainerAwareCommand中你必须使用event_dispatcher的服务 .
ClientCommand.php
使用此服务后,我的事件会触发侦听器 .
这是标签的
name: kernel.event_listener
只是一个提示,以使这更好 .
由于 Symfony 3.3+ 中的依赖注入更改,您可以将许多容易出错的代码委托给Symfony .
简化服务注册
它不适用于听众,因为有额外的标签,但它确实适用于订阅者 - 我建议使用它们来防止任何额外的冗余配置编排 .
获取参数清洁方式 - 通过构造函数
使用它,您可以在开箱即用的命令中使用构造函数注入 .
要阅读有关DI更改的更多信息,请参阅this post with before/after examples .