避免使用原则侦听器的递归循环的一种方法是让侦听器在执行任何更新/持久化之前从事件管理器中删除自己。
因此,例如,在一些代码中,我对我的工作有这样的事情:
// $evm is the Event Manager grabbed from the Entity Manager that
// is part of the Event passed to the listener function
public function removeThyself($evm)
{
$evm->removeEventListener(Events::postFlush, $this);
$evm->removeEventListener(Events::onFlush, $this);
}
public function readdTheyself($evm)
{
$evm->addEventListener(Events::postFlush, $this);
$evm->addEventListener(Events::onFlush, $this);
}
如果这些功能从注册侦听任何事件移除事件侦听器。
然后,在从影响数据库的侦听器执行任何操作之前,我会调用这些来确保事件侦听器不会被调用。例如
// $em is the Entity Manager, $evm is the Event Manager
$this->removeThyself($evm);
$em->flush($toFlush);
$this->readdTheyself($evm);
当我做'addEventListener'它似乎再次调用监听器?我在侦听器的末尾做了一个flush,我可以添加remove侦听器并且不会重新调用,但是如果我在所有东西之后添加了add listener,它似乎仍然是重复的 – 2013-03-18 10:38:04
@AndrewAtkinson我不确定我是否理解。你能提供一个代码示例吗? – 2013-03-18 16:30:43
没关系,几个小时就解决了,对我来说主要问题是,当我试图删除监听器时,它实际上是一个不同的对象(但同一个类),所以'$ this'不起作用。 – 2013-03-19 11:51:25