Doctrine orm 由用户引用在zf2项目的条令实体中的PrePersist上创建的集合

Doctrine orm 由用户引用在zf2项目的条令实体中的PrePersist上创建的集合,doctrine-orm,zend-framework2,zfcuser,Doctrine Orm,Zend Framework2,Zfcuser,在我的zf2项目中,我拥有doctrine 2实体,这些实体引用了由以下人员创建的用户实体: /** * @ORM\ManyToOne(targetEntity="User") * @ORM\JoinColumn(name="created_by", referencedColumnName="id") **/ protected $createdBy; 我想在预科中设置这个引用,我该怎么做? 我尝试了以下方法(我不知道是否正确): 但是主要的问题是,$userId是一个整数,creat

在我的zf2项目中,我拥有doctrine 2实体,这些实体引用了由以下人员创建的用户实体:

/**
 * @ORM\ManyToOne(targetEntity="User")
 * @ORM\JoinColumn(name="created_by", referencedColumnName="id")
 **/
protected $createdBy;
我想在
预科
中设置这个引用,我该怎么做? 我尝试了以下方法(我不知道是否正确):

但是主要的问题是,
$userId
是一个整数,
createdBy
必须保存用户的引用,而不是用户ID


有更好的方法吗?如果否,如何获取引用而不是用户ID?

您可以配置
Zend\Authentication\AuthenticationService
来处理经过身份验证的身份,而不是直接访问会话存储

然后,您可以将
Namespace\For\Entity\User
设置为您的AuthenticationService标识,并通过setter注入注入身份验证服务(请参阅关于挂接到条令生命周期事件)

那么您应该能够做到这一点:

/** @ORM\PrePersist */
public function prePersist() {
    if (empty($this->createdBy)) {
        $this->setCreatedBy($this->getAuthenticationService()->getIdentity());
    }
}
…或者您可以将$loggedInUser属性添加到实体中,并直接注入登录用户,而不是在AuthenticationService(或会话存储)上创建依赖项。这可能是更好的方法,因为它简化了测试:

/** @ORM\PrePersist */
public function prePersist() {
    if (empty($this->createdBy)) {
        $this->setCreatedBy($this->getLoggedInUser());
    }
}
请注意,我通过使用setter摆脱了prePersist方法中的类型检查,因为这样您就可以通过setter中的类型暗示来处理它,如下所示:

public function setAuthenticationService(\Zend\Authentication\AuthenticationService $authenticationService){/** do stuff */};

public function setLoggedInUser(\Namespace\For\Entity\User $user){/** do stuff */};

public function setCreatedBy(\Namespace\For\Entity\User $user){/** do stuff */};

非常感谢你,你给了我比我想要的更多的帮助…:)
public function setAuthenticationService(\Zend\Authentication\AuthenticationService $authenticationService){/** do stuff */};

public function setLoggedInUser(\Namespace\For\Entity\User $user){/** do stuff */};

public function setCreatedBy(\Namespace\For\Entity\User $user){/** do stuff */};