当我注册一个新的质粒实体时,我想给他一个自动名称(如:p0001,p0002,p0003),要做到这一点,我需要在数据库中为特定用户选择最后一个质粒实体,得到它的autoName,并使用此以前的名称来定义新名称。
但是,当我在我的监听器中注入token_storage时,令牌为空...在控制器中,我可以让用户,它的工作。
service.yml
app.event_listener.plasmid:
class: AppBundle\EventListener\PlasmidListener
arguments: ["@security.token_storage"]
tags:
- { name: doctrine.event_listener, event: prePersist }
并且,PlasmidListener
class PlasmidListener
{
private $user;
public function __construct(TokenStorage $tokenStorage)
{
$this->user = $tokenStorage->getToken()->getUser();
}
public function prePersist(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
// If the entity is not a Plasmid, return
if (!$entity instanceof Plasmid) {
return;
}
// Else, we have a Plasmid, get the entity manager
$em = $args->getEntityManager();
// Get the last plasmid Name
$lastPlasmid = $em->getRepository('AppBundle:Plasmid')->findLastPlasmid($this->user);
// Do something with the last plasmid in the database
}
}
如果有人知道为什么我可以在Doctrine Listener中获得实际用户?
由于
答案 0 :(得分:5)
我认为您应该在服务中存储指向tokenStorage类的指针而不是用户对象:
class PlasmidListener
{
private $tokenStorage;
public function __construct(TokenStorage $tokenStorage)
{
$this->tokenStorage = $tokenStorage;
}
public function prePersist(LifecycleEventArgs $args)
{
$user = $this->tokenStorage->getToken()->getUser();
//...
}
}
答案 1 :(得分:0)
为了避免 Symfony4 及以上版本的错误,使用 TokenStorageInterface 而不是 TokenStorage
例如
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
在你的构造函数中:
public function __construct(TokenStorageInterface $tokenStorage)
{
$this->tokenStorage = $tokenStorage;
}
要在 prePersist 中获取用户及其详细信息:
$user = $this->tokenStorage->getToken()->getUser();