How would you add an event listener (in my case it's a doctrine event) dynamically to the kernel without using services.yml pattern?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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: Company\MyBundle\Listener\MyListener
arguments: [@security.context, @logger]
tags:
-
name: doctrine.event_listener
event: preRemove
-
name: doctrine.event_listener
event: onFlush
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');
}