在 Doctrine EventListener 中获取用户 [英] Get User in a Doctrine EventListener
问题描述
当我注册一个新的质粒实体时,我想给他一个自动名称(如:p0001、p0002、p0003),为此,我需要在数据库中为特定用户选择最后一个质粒实体,获取其autoName,并使用以前的名称定义新名称.
when I register a new Plasmid Entity, I want give him an automatic name (like: p0001, p0002, p0003), to do this, I need to select in the database the last Plasmid entity for a specific User, get its autoName, and use this previous name to define the new one.
但是,当我在侦听器中注入 token_storage 时,令牌为空...在控制器中,我可以拥有用户,它可以工作.
But, when I inject the token_storage in my listener, the token is null... In the controller, I can have the user, it's work.
service.yml
The service.yml
app.event_listener.plasmid:
class: AppBundle\EventListener\PlasmidListener
arguments: ["@security.token_storage"]
tags:
- { name: doctrine.event_listener, event: prePersist }
还有 PlasmidListener
And, the 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 中获取实际用户?
If someone know why I can get the actual user in the Doctrine Listener ?
谢谢
推荐答案
我认为你应该在你的服务中存储指向 tokenStorage 类的指针而不是用户对象:
I think that you should store pointer to tokenStorage class in your service instead of user object:
class PlasmidListener
{
private $tokenStorage;
public function __construct(TokenStorage $tokenStorage)
{
$this->tokenStorage = $tokenStorage;
}
public function prePersist(LifecycleEventArgs $args)
{
$user = $this->tokenStorage->getToken()->getUser();
//...
}
}
这篇关于在 Doctrine EventListener 中获取用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!