2011-12-30 22 views
0

我使用Symfony的2學說2.我有一個UserListenersymfony docs page)。在堅持用戶時,我想爲User創建一個UserInventory實例。 UserInventory是(單向)關聯的擁有方。無限循環持續,當實體與監聽<code>PrePersist</code> & <code>PreRemove</code>活動的用戶對象事件監聽器

這種設置

不過,我遇到一個無限循環:

class UserListener { 

    /** 
    * Initializes UserInventory for user with initial number of nets 
    */ 
    public function prePersist(LifecycleEventArgs $args) { 
     $em = $args->getEntityManager(); 
     $user = $args->getEntity(); 
     $inventory = new UserInventory(); 
     $inventory->setUser($user); 
     $inventory->setNumNets($this->initialNets); 
     $em->persist($inventory); // if I comment out this line, it works but the inventory is not persisted 
     $em->flush(); 
    } 

} 

這可能是UserInventory是聯想這樣的擁有方,它會嘗試再次保存用戶造成這種功能再次叫什麼?我怎樣才能解決這個問題?

我希望我的UserInventory擁有這裏的關聯,因爲它在「正確的」包中。我有一個UserBundle但我不認爲庫存類應該在那裏。

UPDATEError/Log

回答

1

您添加的偵聽器在應用程序中所有的entites。當然,當你堅持任何物體時,例如UserInventory,prePersist將被一次又一次地調用。 因爲symfony文件說,你可以簡單地做一個檢查:

if ($user instanceof User) { 
     $inventory = new UserInventory(); 
     $inventory->setUser($user); 
     $inventory->setNumNets($this->initialNets); 
     $em->persist($inventory); 
    } 

另外,我建議閱讀doctrine2約events