1. 首页
  2. 其他

Symfony2 动态添加事件监听器

本文介绍了Symfony2 动态添加事件监听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不使用 services.yml 模式的情况下向内核动态添加事件监听器(在我的例子中是一个教义事件)?

How would you add an event listener (in my case it’s a doctrine event) dynamically to the kernel without using services.yml pattern?

推荐答案

在对供应商目录和 appProdProjectContainer.php 文件进行了一些挖掘之后,我自己找到了答案.如果您希望将事件注册到事件管理器,则必须在 services.yml 中为您希望触发的事件指定标签,例如:

I found the answer myself after doing some digging into the vendor directory and appProdProjectContainer.php file. If you want your events to be registered with event manager you have to specify the tags in your services.yml for the events that you want this to trigger for like:

  event_listener:
      class: CompanyMyBundleListenerMyListener
      arguments: [@security.context, @logger]
      tags:
          -   
              name: doctrine.event_listener
              event: preRemove
          -   
              name: doctrine.event_listener
              event: onFlush

现在如果你想动态注册这些事件,你需要将 event_listener 资源留在 services.yml 中,但删除标签部分并动态添加它们关注:

Now if you want to dynamically register these events, you need to leave the event_listener resource in services.yml, but delete the tags part and dynamically add them that as follow:

if (something) {
  $evm = $em->getConnection()->getEventManager();
  $evm->addEventListener(
      [
        0 => 'preRemove',
        1 => 'onFlush'
      ],
      $this->container->get('event_listener');
}

这篇关于Symfony2 动态添加事件监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,WP2

Symfony2 动态添加事件监听器 为WP2原创文章,链接:https://www.wp2.cn/other/symfony2-%e5%8a%a8%e6%80%81%e6%b7%bb%e5%8a%a0%e4%ba%8b%e4%bb%b6%e7%9b%91%e5%90%ac%e5%99%a8/