Post Persist在持久化之后创建另一个实体

时间:2013-11-15 03:15:53

标签: zend-framework doctrine-orm doctrine zend-framework2

我希望能够在用户注册后自动创建用户个人资料。我附加了一个post persist函数来创建一个用户配置文件对象,但我没有访问实体管理器来持久保存该对象。解决这个问题的最佳方式是什么?

//user.php
/**
 * @ORM\PostPersist()
 */
public function PostPersistAction()
{
    //create a user profile when a user is created.
    $userprofile = new Profile();
    $userprofile->setCreatedAt(new \DateTime("now"));
    $userprofile->__set('user', $this);

    $em = $this->getEntityManager(); //doesn't work because getServiceLocator()->get('doctrine..') fails
    $em->persist($userprofile);
    $em->flush();

}

1 个答案:

答案 0 :(得分:0)

解决方案:

/**
 * @ORM\PostPersist()
 */
public function PostPersistAction(LifecycleEventArgs $eventArgs)
{
    $entity = $eventArgs->getEntity();
    $em = $eventArgs->getEntityManager();

    if ($entity instanceof User) {
        //create a user profile when a user is created.
        $userprofile = new Profile();
        $userprofile->setCreatedAt(new \DateTime("now"));
        $userprofile->__set('user', $this);

        $em->persist($userprofile);
        $em->flush();
    }

}