使用 Api 平台,自动将用户分配给对象 (OneToMany)
Using Api Platform, automatically assign user to Object (OneToMany)
这是我的场景:
我有一个 Article
实体。每篇文章都有一个所有者(User
)。一个用户可以拥有多篇文章。用户可以 post 一篇文章超过 API。
我希望根据 Bearer 令牌自动设置文章的 user_id
列(我正在使用 JWT 身份验证)。
我在任何地方都找不到有关如何执行此操作的任何文档。有人可以帮助实现这一目标吗?
注意:如果可能的话,我正在寻找可以避免在 Symfony 中使用额外扩展(或控制器)的解决方案。我相信 Api 平台应该能够使用内置技术实现这一点,但我可能错了。
这是我的实体:
用户:
<?php
namespace App\Entity;
use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* @ApiResource()
* @ORM\Table(name="users")
* @ORM\Entity(repositoryClass="App\Repository\UserRepository")
* @UniqueEntity(fields="email", message="Email already taken")
*/
class User implements UserInterface, \Serializable
{
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string $password
*
* @ORM\Column(type="string", length=64)
* @Assert\NotBlank()
*/
private $password;
/**
* @var string $plainPassword
*
* @Assert\NotBlank()
* @Assert\Length(max=4096)
*/
private $plainPassword;
/**
* @var string $email
*
* @ORM\Column(type="string", length=254, unique=true)
* @Assert\NotBlank()
* @Assert\Email()
*/
private $email;
/**
* @var bool $isActive
*
* @ORM\Column(name="is_active", type="boolean")
*/
private $isActive;
/**
* @ORM\OneToMany(targetEntity="Article", mappedBy="user")
*/
private $articles;
/**
* @ORM\Column(type="array")
*/
private $roles;
public function __construct($email)
{
$this->isActive = true;
$this->email = $email;
$this->articles = new ArrayCollection();
}
public function getId()
{
return $this->id;
}
/**
* @return string
*/
public function getUsername()
{
return $this->email;
}
/**
* @return string
*/
public function getEmail()
{
return $this->email;
}
/**
* @param string $email
*
* @return $this
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* @return null|string
*/
public function getSalt()
{
return null;
}
/**
* @return string
*/
public function getPassword()
{
return $this->password;
}
/**
* @param string $password
*
* @return $this
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* @return array
*/
public function getRoles()
{
return ['ROLE_USER'];
}
public function eraseCredentials()
{
}
/** @see \Serializable::serialize() */
public function serialize()
{
return serialize(array(
$this->id,
$this->email,
$this->password,
));
}
/** @see \Serializable::unserialize()
* @param $serialized
*/
public function unserialize($serialized)
{
list (
$this->id,
$this->email,
$this->password,
) = unserialize($serialized, array('allowed_classes' => false));
}
}
文章
<?php
namespace App\Entity;
use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* A User's article
*
* @ORM\Table(name="articles")
* @ApiResource(
* attributes={"access_control"="is_granted('ROLE_USER')"},
* collectionOperations={
* "get",
* "post"={"access_control"="is_granted('ROLE_USER')"}
* },
* itemOperations={
* "get"={"access_control"="is_granted('ROLE_USER') and object.owner == user"}
* }
* )
* @ORM\Entity
* @ORM\HasLifecycleCallbacks()
*/
class Article
{
/**
* @var int $id
*
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @var string $user
*
* @ORM\ManyToOne(targetEntity="User", inversedBy="articles")
*/
private $user;
/**
* @var string $name
*
* @ORM\Column(type="text")
* @Assert\NotBlank()
*/
private $name;
/**
* @var string $location
*
* @ORM\Column(type="text")
*/
private $location;
/**
* @var \DateTimeInterface $createdAt
*
* @ORM\Column(type="datetime_immutable")
*/
private $createdAt;
/**
* @var \DateTimeInterface $updatedAt
*
* @ORM\Column(type="date_immutable", nullable=true)
*/
private $updatedAt;
/**
* @ORM\PrePersist()
*/
public function setCreatedAt()
{
$this->createdAt = new \DateTime();
}
/**
* @ORM\PreUpdate()
*/
public function setUpdatedAt()
{
$this->updatedAt = new \DateTime();
}
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* @param int $id
*/
public function setId(int $id): void
{
$this->id = $id;
}
/**
* @return string
*/
public function getUser(): string
{
return $this->user;
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @param string $name
*/
public function setName(string $name): void
{
$this->name = $name;
}
/**
* @return string
*/
public function getLocation(): string
{
return $this->location;
}
/**
* @param string $location
*/
public function setLocation(string $location): void
{
$this->location = $location;
}
}
这应该可以使用 EventListener
: https://api-platform.com/docs/core/events
有了这些,您就可以在没有新控制器的情况下挂接到 ApiPlatform 进程的内部进程。非常适合您的用例。
实现可能如下所示:
<?php
// api/src/EventSubscriber/AddOwnerToArticleSubscriber.php
namespace App\EventSubscriber;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\Article;
use App\Entity\User;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
final class AddOwnerToArticleSubscriber implements EventSubscriberInterface
{
/**
* @var TokenStorageInterface
*/
private $tokenStorage;
public function __construct(TokenStorageInterface $tokenStorage)
{
$this->tokenStorage = $tokenStorage;
}
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => ['attachOwner', EventPriorities::PRE_WRITE],
];
}
public function attachOwner(GetResponseForControllerResultEvent $event)
{
$article = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
if (!$article instanceof Article || Request::METHOD_POST !== $method) {
// Only handle Article entities (Event is called on any Api entity)
return;
}
// maybe these extra null checks are not even needed
$token = $this->tokenStorage->getToken();
if (!$token) {
return;
}
$owner = $token->getUser();
if (!$owner instanceof User) {
return;
}
// Attach the user to the not yet persisted Article
$article->setUser($owner);
}
}
您可以创建一个名为 Base 的实体,并且在此 class 中您可以有一些 属性 如“createdBy”、“modifiedBy”、“createdAt”、“modifiedAt”、“status” .
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation\Groups;
/**
* @ORM\MappedSuperclass()
*/
class Base implements PublishedInfoEntityInterface
{
/**
* @ORM\Column(type="datetime", nullable=true)
*/
private $createdAt;
/**
* @ORM\Column(type="datetime", nullable=true)
*/
private $modifiedAt;
/**
* @ORM\ManyToOne(targetEntity="User")
* @ORM\JoinColumn(nullable=true)
*/
private $createdBy;
/**
* @ORM\ManyToOne(targetEntity="User")
* @ORM\JoinColumn(nullable=true)
*/
private $modifiedBy;
/**
* @ORM\Column(type="integer", nullable=true, length=2)
*/
private $status;
public function getCreatedAt()
{
return $this->createdAt;
}
public function setCreatedAt(\DateTimeInterface $createdAt): PublishedInfoEntityInterface
{
$this->createdAt = $createdAt;
return $this;
}
public function getModifiedAt()
{
return $this->modifiedAt;
}
public function setModifiedAt(\DateTimeInterface $modifiedAt): PublishedInfoEntityInterface
{
$this->modifiedAt = $modifiedAt;
return $this;
}
/**
* @return User
*/
public function getCreatedBy()
{
return $this->createdBy;
}
/**
* @param User $createdBy
* @return Base
*/
public function setCreatedBy($createdBy): self
{
$this->createdBy = $createdBy;
return $this;
}
/**
* @return User
*/
public function getModifiedBy()
{
return $this->modifiedBy;
}
/**
* @param User $modifiedBy
* @return Base
*/
public function setModifiedBy($modifiedBy): self
{
$this->modifiedBy = $modifiedBy;
return $this;
}
/**
* @return int
*/
public function getStatus()
{
return $this->status;
}
/**
* @param integer $status
*/
public function setStatus($status): void
{
$this->status = $status;
return $this;
}
}
创建订阅者class 设置自动createdBy 和modifiedBy 像这样的代码
<?php
namespace App\EventSubscriber;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\Base;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Security;
class AuthoredEntitySubscriber implements EventSubscriberInterface
{
private $entityManager;
/**
* @var Security
*/
private $security;
public function __construct(EntityManagerInterface $entityManager,Security $security)
{
$this->entityManager = $entityManager;
$this->security = $security;
}
public static function getSubscribedEvents()
{
return [KernelEvents::VIEW => ['setAuthor', EventPriorities::PRE_WRITE]];
}
public function setAuthor(ViewEvent $event)
{
$entity = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
$role = $this->security->getToken()->getRoleNames();
if (!$entity instanceof Base || !in_array($method, [Request::METHOD_POST, Request::METHOD_PUT]) || !$role) {
return;
}
$entity->setModifiedBy($this->security->getUser());
if (Request::METHOD_POST === $method) {
$entity->setCreatedBy($this->security->getUser());
}
}
}
如果您想添加自动创建的 createdAt 和 modifiedAt,您必须为 createdAt 和 modifiedAt 创建一个名为 PublishedInfoEntityInterface 的接口 class,并且 class 编写此代码:
<?php
namespace App\Entity;
interface PublishedInfoEntityInterface
{
public function setCreatedAt(\DateTimeInterface $dateTime): PublishedInfoEntityInterface;
public function setModifiedAt(\DateTimeInterface $dateTime): PublishedInfoEntityInterface;
}
并像这样创建自动填充 createdAt 和 modifiedAt 的订阅者
<?php
namespace App\EventSubscriber;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\PublishedInfoEntityInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class PublishedInfoEntitySubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return [KernelEvents::VIEW => ['setDataTime', EventPriorities::PRE_WRITE]];
}
public function setDataTime(ViewEvent $event)
{
$entity = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
if (!$entity instanceof PublishedInfoEntityInterface || !in_array($method, [Request::METHOD_POST, Request::METHOD_PUT])) {
return;
}
$entity->setCreatedAt(new \DateTime());
if (Request::METHOD_POST === $method){
$entity->setModifiedAt(new \DateTime());
}
}
}
最后,每个 class 你想要那些 属性 你只需像这样扩展这个 class
class User extends Base implements UserInterface
并创建迁移,
另一种方法是使用 Doctrine Entity Listener。
class SetUserListener
{
private Security $security;
public function __construct(Security $security)
{
$this->security = $security;
}
public function prePersist($obj)
{
if (!is_a($obj, Timer::class) &&
!is_a($obj, DailySummary::class) &&
!is_a($obj, Task::class)
) {
return;
}
if ($this->security->getUser()) {
$obj->setUser($this->security->getUser());
}
}
}
确保在您的服务中连接实体侦听器
App\Doctrine\SetUserListener:
tags: [ doctrine.orm.entity_listener ]
就我而言,我使用的是 Gedmo 包和 Blameable 注释。我创建了一个特征而不是像下面这样的映射超级 class :
<?php
namespace App\ORM\Traits;
use App\Entity\User;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
trait OwnerTrait
{
/**
* @var User|null
* @ORM\ManyToOne(targetEntity="App\Entity\User")
* @ORM\JoinColumn(name="created_by", referencedColumnName="id", nullable=true, onDelete="SET NULL")
*
* @Gedmo\Blameable(on="create")
*/
protected ?User $createdBy;
/**
* @var User|null
* @ORM\ManyToOne(targetEntity="App\Entity\User")
* @ORM\JoinColumn(name="updated_by", referencedColumnName="id", nullable=true, onDelete="SET NULL")
*
* @Gedmo\Blameable(on="update")
*/
protected ?User $updatedBy;
/**
* Set createdBy
* @param User|null $createdBy
* @return $this
*/
public function setCreatedBy(?User $createdBy)
{
$this->createdBy = $createdBy;
return $this;
}
/**
* Returns the user who create the object
* @return User|null
*/
public function getCreatedBy(): ?User
{
return $this->createdBy;
}
/**
* Set updatedBy
* @param User|null $updatedBy
* @return $this
*/
public function setUpdatedBy(?User $updatedBy)
{
$this->updatedBy = $updatedBy;
return $this;
}
/**
* Returns user who is the last to modify object
* @return User|null
*/
public function getUpdatedBy(): ?User
{
return $this->updatedBy;
}
}
在实体上
<?php
class Article
{
use OwnerTrait;
}
这是我的场景:
我有一个 Article
实体。每篇文章都有一个所有者(User
)。一个用户可以拥有多篇文章。用户可以 post 一篇文章超过 API。
我希望根据 Bearer 令牌自动设置文章的 user_id
列(我正在使用 JWT 身份验证)。
我在任何地方都找不到有关如何执行此操作的任何文档。有人可以帮助实现这一目标吗?
注意:如果可能的话,我正在寻找可以避免在 Symfony 中使用额外扩展(或控制器)的解决方案。我相信 Api 平台应该能够使用内置技术实现这一点,但我可能错了。
这是我的实体:
用户:
<?php
namespace App\Entity;
use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* @ApiResource()
* @ORM\Table(name="users")
* @ORM\Entity(repositoryClass="App\Repository\UserRepository")
* @UniqueEntity(fields="email", message="Email already taken")
*/
class User implements UserInterface, \Serializable
{
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string $password
*
* @ORM\Column(type="string", length=64)
* @Assert\NotBlank()
*/
private $password;
/**
* @var string $plainPassword
*
* @Assert\NotBlank()
* @Assert\Length(max=4096)
*/
private $plainPassword;
/**
* @var string $email
*
* @ORM\Column(type="string", length=254, unique=true)
* @Assert\NotBlank()
* @Assert\Email()
*/
private $email;
/**
* @var bool $isActive
*
* @ORM\Column(name="is_active", type="boolean")
*/
private $isActive;
/**
* @ORM\OneToMany(targetEntity="Article", mappedBy="user")
*/
private $articles;
/**
* @ORM\Column(type="array")
*/
private $roles;
public function __construct($email)
{
$this->isActive = true;
$this->email = $email;
$this->articles = new ArrayCollection();
}
public function getId()
{
return $this->id;
}
/**
* @return string
*/
public function getUsername()
{
return $this->email;
}
/**
* @return string
*/
public function getEmail()
{
return $this->email;
}
/**
* @param string $email
*
* @return $this
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* @return null|string
*/
public function getSalt()
{
return null;
}
/**
* @return string
*/
public function getPassword()
{
return $this->password;
}
/**
* @param string $password
*
* @return $this
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* @return array
*/
public function getRoles()
{
return ['ROLE_USER'];
}
public function eraseCredentials()
{
}
/** @see \Serializable::serialize() */
public function serialize()
{
return serialize(array(
$this->id,
$this->email,
$this->password,
));
}
/** @see \Serializable::unserialize()
* @param $serialized
*/
public function unserialize($serialized)
{
list (
$this->id,
$this->email,
$this->password,
) = unserialize($serialized, array('allowed_classes' => false));
}
}
文章
<?php
namespace App\Entity;
use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* A User's article
*
* @ORM\Table(name="articles")
* @ApiResource(
* attributes={"access_control"="is_granted('ROLE_USER')"},
* collectionOperations={
* "get",
* "post"={"access_control"="is_granted('ROLE_USER')"}
* },
* itemOperations={
* "get"={"access_control"="is_granted('ROLE_USER') and object.owner == user"}
* }
* )
* @ORM\Entity
* @ORM\HasLifecycleCallbacks()
*/
class Article
{
/**
* @var int $id
*
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @var string $user
*
* @ORM\ManyToOne(targetEntity="User", inversedBy="articles")
*/
private $user;
/**
* @var string $name
*
* @ORM\Column(type="text")
* @Assert\NotBlank()
*/
private $name;
/**
* @var string $location
*
* @ORM\Column(type="text")
*/
private $location;
/**
* @var \DateTimeInterface $createdAt
*
* @ORM\Column(type="datetime_immutable")
*/
private $createdAt;
/**
* @var \DateTimeInterface $updatedAt
*
* @ORM\Column(type="date_immutable", nullable=true)
*/
private $updatedAt;
/**
* @ORM\PrePersist()
*/
public function setCreatedAt()
{
$this->createdAt = new \DateTime();
}
/**
* @ORM\PreUpdate()
*/
public function setUpdatedAt()
{
$this->updatedAt = new \DateTime();
}
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* @param int $id
*/
public function setId(int $id): void
{
$this->id = $id;
}
/**
* @return string
*/
public function getUser(): string
{
return $this->user;
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @param string $name
*/
public function setName(string $name): void
{
$this->name = $name;
}
/**
* @return string
*/
public function getLocation(): string
{
return $this->location;
}
/**
* @param string $location
*/
public function setLocation(string $location): void
{
$this->location = $location;
}
}
这应该可以使用 EventListener
: https://api-platform.com/docs/core/events
有了这些,您就可以在没有新控制器的情况下挂接到 ApiPlatform 进程的内部进程。非常适合您的用例。
实现可能如下所示:
<?php
// api/src/EventSubscriber/AddOwnerToArticleSubscriber.php
namespace App\EventSubscriber;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\Article;
use App\Entity\User;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
final class AddOwnerToArticleSubscriber implements EventSubscriberInterface
{
/**
* @var TokenStorageInterface
*/
private $tokenStorage;
public function __construct(TokenStorageInterface $tokenStorage)
{
$this->tokenStorage = $tokenStorage;
}
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => ['attachOwner', EventPriorities::PRE_WRITE],
];
}
public function attachOwner(GetResponseForControllerResultEvent $event)
{
$article = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
if (!$article instanceof Article || Request::METHOD_POST !== $method) {
// Only handle Article entities (Event is called on any Api entity)
return;
}
// maybe these extra null checks are not even needed
$token = $this->tokenStorage->getToken();
if (!$token) {
return;
}
$owner = $token->getUser();
if (!$owner instanceof User) {
return;
}
// Attach the user to the not yet persisted Article
$article->setUser($owner);
}
}
您可以创建一个名为 Base 的实体,并且在此 class 中您可以有一些 属性 如“createdBy”、“modifiedBy”、“createdAt”、“modifiedAt”、“status” .
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation\Groups;
/**
* @ORM\MappedSuperclass()
*/
class Base implements PublishedInfoEntityInterface
{
/**
* @ORM\Column(type="datetime", nullable=true)
*/
private $createdAt;
/**
* @ORM\Column(type="datetime", nullable=true)
*/
private $modifiedAt;
/**
* @ORM\ManyToOne(targetEntity="User")
* @ORM\JoinColumn(nullable=true)
*/
private $createdBy;
/**
* @ORM\ManyToOne(targetEntity="User")
* @ORM\JoinColumn(nullable=true)
*/
private $modifiedBy;
/**
* @ORM\Column(type="integer", nullable=true, length=2)
*/
private $status;
public function getCreatedAt()
{
return $this->createdAt;
}
public function setCreatedAt(\DateTimeInterface $createdAt): PublishedInfoEntityInterface
{
$this->createdAt = $createdAt;
return $this;
}
public function getModifiedAt()
{
return $this->modifiedAt;
}
public function setModifiedAt(\DateTimeInterface $modifiedAt): PublishedInfoEntityInterface
{
$this->modifiedAt = $modifiedAt;
return $this;
}
/**
* @return User
*/
public function getCreatedBy()
{
return $this->createdBy;
}
/**
* @param User $createdBy
* @return Base
*/
public function setCreatedBy($createdBy): self
{
$this->createdBy = $createdBy;
return $this;
}
/**
* @return User
*/
public function getModifiedBy()
{
return $this->modifiedBy;
}
/**
* @param User $modifiedBy
* @return Base
*/
public function setModifiedBy($modifiedBy): self
{
$this->modifiedBy = $modifiedBy;
return $this;
}
/**
* @return int
*/
public function getStatus()
{
return $this->status;
}
/**
* @param integer $status
*/
public function setStatus($status): void
{
$this->status = $status;
return $this;
}
}
创建订阅者class 设置自动createdBy 和modifiedBy 像这样的代码
<?php
namespace App\EventSubscriber;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\Base;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Security;
class AuthoredEntitySubscriber implements EventSubscriberInterface
{
private $entityManager;
/**
* @var Security
*/
private $security;
public function __construct(EntityManagerInterface $entityManager,Security $security)
{
$this->entityManager = $entityManager;
$this->security = $security;
}
public static function getSubscribedEvents()
{
return [KernelEvents::VIEW => ['setAuthor', EventPriorities::PRE_WRITE]];
}
public function setAuthor(ViewEvent $event)
{
$entity = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
$role = $this->security->getToken()->getRoleNames();
if (!$entity instanceof Base || !in_array($method, [Request::METHOD_POST, Request::METHOD_PUT]) || !$role) {
return;
}
$entity->setModifiedBy($this->security->getUser());
if (Request::METHOD_POST === $method) {
$entity->setCreatedBy($this->security->getUser());
}
}
}
如果您想添加自动创建的 createdAt 和 modifiedAt,您必须为 createdAt 和 modifiedAt 创建一个名为 PublishedInfoEntityInterface 的接口 class,并且 class 编写此代码:
<?php
namespace App\Entity;
interface PublishedInfoEntityInterface
{
public function setCreatedAt(\DateTimeInterface $dateTime): PublishedInfoEntityInterface;
public function setModifiedAt(\DateTimeInterface $dateTime): PublishedInfoEntityInterface;
}
并像这样创建自动填充 createdAt 和 modifiedAt 的订阅者
<?php
namespace App\EventSubscriber;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\PublishedInfoEntityInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class PublishedInfoEntitySubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return [KernelEvents::VIEW => ['setDataTime', EventPriorities::PRE_WRITE]];
}
public function setDataTime(ViewEvent $event)
{
$entity = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
if (!$entity instanceof PublishedInfoEntityInterface || !in_array($method, [Request::METHOD_POST, Request::METHOD_PUT])) {
return;
}
$entity->setCreatedAt(new \DateTime());
if (Request::METHOD_POST === $method){
$entity->setModifiedAt(new \DateTime());
}
}
}
最后,每个 class 你想要那些 属性 你只需像这样扩展这个 class
class User extends Base implements UserInterface
并创建迁移,
另一种方法是使用 Doctrine Entity Listener。
class SetUserListener
{
private Security $security;
public function __construct(Security $security)
{
$this->security = $security;
}
public function prePersist($obj)
{
if (!is_a($obj, Timer::class) &&
!is_a($obj, DailySummary::class) &&
!is_a($obj, Task::class)
) {
return;
}
if ($this->security->getUser()) {
$obj->setUser($this->security->getUser());
}
}
}
确保在您的服务中连接实体侦听器
App\Doctrine\SetUserListener:
tags: [ doctrine.orm.entity_listener ]
就我而言,我使用的是 Gedmo 包和 Blameable 注释。我创建了一个特征而不是像下面这样的映射超级 class :
<?php
namespace App\ORM\Traits;
use App\Entity\User;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
trait OwnerTrait
{
/**
* @var User|null
* @ORM\ManyToOne(targetEntity="App\Entity\User")
* @ORM\JoinColumn(name="created_by", referencedColumnName="id", nullable=true, onDelete="SET NULL")
*
* @Gedmo\Blameable(on="create")
*/
protected ?User $createdBy;
/**
* @var User|null
* @ORM\ManyToOne(targetEntity="App\Entity\User")
* @ORM\JoinColumn(name="updated_by", referencedColumnName="id", nullable=true, onDelete="SET NULL")
*
* @Gedmo\Blameable(on="update")
*/
protected ?User $updatedBy;
/**
* Set createdBy
* @param User|null $createdBy
* @return $this
*/
public function setCreatedBy(?User $createdBy)
{
$this->createdBy = $createdBy;
return $this;
}
/**
* Returns the user who create the object
* @return User|null
*/
public function getCreatedBy(): ?User
{
return $this->createdBy;
}
/**
* Set updatedBy
* @param User|null $updatedBy
* @return $this
*/
public function setUpdatedBy(?User $updatedBy)
{
$this->updatedBy = $updatedBy;
return $this;
}
/**
* Returns user who is the last to modify object
* @return User|null
*/
public function getUpdatedBy(): ?User
{
return $this->updatedBy;
}
}
在实体上
<?php
class Article
{
use OwnerTrait;
}