当我注册一个新的质粒实体时,我想给他一个自动名称(例如:p0001、p0002、p0003),为此,我需要在数据库中为特定用户选择最后一个质粒实体,获取其自动名称,然后使用以前的名称来定义新名称。
但是,当我在监听器中注入(inject) token_storage 时, token 为空......在 Controller 中,我可以拥有用户,这是可行的。
服务.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 中获得实际用户?
谢谢
最佳答案
我认为您应该在服务中存储指向 tokenStorage 类的指针,而不是用户对象:
class PlasmidListener
{
private $tokenStorage;
public function __construct(TokenStorage $tokenStorage)
{
$this->tokenStorage = $tokenStorage;
}
public function prePersist(LifecycleEventArgs $args)
{
$user = $this->tokenStorage->getToken()->getUser();
//...
}
}
关于symfony - 在 Doctrine EventListener 中获取用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40087840/