避免使用原則偵聽器的遞歸循環的一種方法是讓偵聽器在執行任何更新/持久化之前從事件管理器中刪除自己。
因此,例如,在一些代碼中,我對我的工作有這樣的事情:
// $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