I am using Symfony 2 with Doctrine 2. I have a UserListener (symfony docs page) that listens to the PrePersist & PreRemove events for User objects. When Persisting a User, I want to create a UserInventory instance for the User. UserInventory is the owning side of the (uni-directional) association.
However with this setup, I encounter an infinite loop:
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();
}
}
It might be that UserInventory is the owning side of the association thus, it tries to persist the user again resulting in this function called again? How can I fix this?
I want my UserInventory to own the association here because its in the “correct” bundle. I have a UserBundle but I dont think the Inventory class should be there.
UPDATE: Error/Log
You added a listener for all entites in your application. Of course, when you persist any object, e.g. UserInventory, prePersist will be called again and again.
As the symfony documentation says you can simply do a check:
Also, I recommend to read about events in doctrine2.