使用事件监听器持久化实体时的无限循环

时间:2011-12-30 07:50:22

标签: symfony doctrine-orm

我正在使用Symfony 2和Doctrine 2.我有一个UserListenersymfony docs page)来监听PrePersist&用户对象的PreRemove个事件。在坚持用户时,我想为UserInventory创建User个实例。 UserInventory是(单向)关联的拥有方。

然而,通过这种设置,我遇到了一个无限循环:

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,但我不认为库存类应该在那里。

更新Error/Log

1 个答案:

答案 0 :(得分:1)

您为应用中的所有entites添加了一个侦听器。当然,当你坚持任何对象,例如UserInventory,prePersist将一次又一次地被调用。 正如symfony文档所说,您可以简单地进行检查:

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

另外,我建议阅读doctrine2中的events

相关问题