문제

In my zf2 project, I have doctrine 2 entities that reference the user entity as created by as the following:

/**
 * @ORM\ManyToOne(targetEntity="User")
 * @ORM\JoinColumn(name="created_by", referencedColumnName="id")
 **/
protected $createdBy;

and I want to set this reference in the PrePersist, how can I do that? I tried the following (I don't know if it is right):

/** @ORM\PrePersist */
public function prePersist() {
    if ($this->createdBy === null) {
        $session = new \Zend\Authentication\Storage\Session;
        $userId = $session->read();
        if ($userId !== null) {
            $this->createdBy = $userId;
        } else {
            throw new \Exception("Invalid User");
        }
    }
}

but the main problem is that the $userId is an integer, and createdBy must hold the reference of the user not the user ID.

is there a better way to do that? if no, how can I get the reference instead of the user ID?

도움이 되었습니까?

해결책

Instead of directly accessing your session storage, you might configuring a Zend\Authentication\AuthenticationService to handle your authenticated identity.

Then you could set your Namespace\For\Entity\User as your AuthenticationService identity and inject the authentication service via setter injection (see this post about hooking into Doctrine lifecycle events).

Then you should be able to do this:

/** @ORM\PrePersist */
public function prePersist() {
    if (empty($this->createdBy)) {
        $this->setCreatedBy($this->getAuthenticationService()->getIdentity());
    }
}

...or you could add a $loggedInUser property to your entity, and inject the logged in User directly, instead of creating a dependency on the AuthenticationService (or session storage). This is probably the better way, because it simplifies your tests:

/** @ORM\PrePersist */
public function prePersist() {
    if (empty($this->createdBy)) {
        $this->setCreatedBy($this->getLoggedInUser());
    }
}

Note that I got rid of the type-checking in your prePersist method by using setters, because then you can handle that via type-hinting in your setters like this:

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 */};
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top