Php Symfony 5-返回Trait中的当前用户数据无效
我创建了一个trait,在每个实体中添加两个属性/列user_created和user_updated,其原理与Web上的timestable trait相同Php Symfony 5-返回Trait中的当前用户数据无效,php,symfony,Php,Symfony,我创建了一个trait,在每个实体中添加两个属性/列user_created和user_updated,其原理与Web上的timestable trait相同 <?php namespace App\Entity; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Security\Core\Security; use Symfony\Component\Security\Core\User\UserInterface\Use
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\UserInterface\UserInterface;
trait UserTrack
{
/**
* @ORM\ManyToOne(targetEntity=User::class)
*/
private $createdUser;
/**
* @ORM\ManyToOne(targetEntity=User::class)
*/
private $updatedUser;
private $security;
private $me;
public function __construct(Security $security, UserInterface $user)
{
$this->security = $security;
// $this->me = $this->getUser()->getId(); //ERROR
// $this->me = $this->security->getUser()->getId(); //ERROR
// $this->me = $user->getId(); //ERROR
}
/**
* @ORM\PrePersist
*/
public function setCreatedUserAutomatically()
{
if ($this->getCreatedUser() === null) {
$this->setCreatedUser($this->me);
}
}
/**
* @ORM\PreUpdate
*/
public function setUpdatedUserAutomatically()
{
$this->setUpdatedUser($this->me);
}
}
如您所见,我添加了一个构造方法,试图获取我的用户对象,但它不起作用
你能帮我吗
谢谢 多亏了Jakumi和Julien B,以下代码完成了这项工作: EventListener\EntityListener.php
<?php
namespace App\EventListener;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Event\PreUpdateEventArgs;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class EntityListener
{
private $tokenStorage;
public function __construct(TokenStorageInterface $tokenStorage = null)
{
$this->tokenStorage = $tokenStorage;
}
public function prePersist(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
if (null !== $currentUser = $this->getUser()) {
$entity->setCreatedUser($currentUser);
}
}
public function preUpdate(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
if (null !== $currentUser = $this->getUser()) {
$entity->setUpdatedUser($currentUser);
}
}
public function getUser()
{
if (!$this->tokenStorage) {
throw new \LogicException('The SecurityBundle is not registered in your application.');
}
if (null === $token = $this->tokenStorage->getToken()) {
return;
}
if (!is_object($user = $token->getUser())) {
// e.g. anonymous authentication
return;
}
return $user;
}
}
由于trait本身不起任何作用,因此它必须通过trait UserTrack包含在某个地方,并且它所在的类很可能有自己的u构造方法,该方法将覆盖trait的。作为一般规则,特征不应该包含构造方法。此外,实体通常不应该访问安全性或用户界面,因为它违反了关注点分离。一个实体应该只关心它所持有的数据,保持一致性。@Jakumi是对的,我认为在这种情况下使用实体侦听器会更好
my.listener:
class: App\EventListener\EntityListener
arguments: ['@security.token_storage']
tags:
- { name: doctrine.event_listener, event: prePersist }
- { name: doctrine.event_listener, event: preUpdate }