Symfony 侦听器 - postUpdate doublon
Symfony listener - postUpdate doublon
我是 运行 Symfony 3 LTS。
我有一个订阅者正在监听 postUpdate
事件,以便将我数据库中产品的所有 activity 登录到数据库。下面是我的代码:
use AppBundle\Entity\History;
public function getSubscribedEvents()
{
return [
Events::postUpdate,
];
}
public function postUpdate(LifecycleEventArgs $args)
{
if(!is_null($this->tokenStorage->getToken())) {
$user = $this->tokenStorage->getToken()->getUser();
$entity = $args->getObject();
$em = $args->getEntityManager();
if ($entity instanceof Product) {
$history = new History($user, "Product #5 has been updated");
$em->persist($history);
}
$em->flush();
}
}
问题:History
在数据库中插入了两次。我不知道为什么。我试图删除 persist()
and/or flush()
方法,但没有创建任何内容。
PS:我的实体 Product
和 History
之间没有关系。它一定不会。我的问题只是重复行为。
我没有正确答案,但有一个解决方法:
use AppBundle\Entity\History;
// Will contains the User ID to avoid duplicate log
private $flushed = [];
public function getSubscribedEvents()
{
return [
Events::postUpdate,
];
}
public function postUpdate(LifecycleEventArgs $args)
{
if(!is_null($this->tokenStorage->getToken())) {
$user = $this->tokenStorage->getToken()->getUser();
$entity = $args->getObject();
$em = $args->getEntityManager();
// Check that the User.id is not already created in History during the update PHP Process
if ($entity instanceof Product && !in_array($user->getId(), $this->flushed)) {
$history = new History($user, "Product #5 has been updated");
$em->persist($history);
// Add the user ID in our array to avoid duplicate
$this->flushed[] = $user->getId();
}
$em->flush();
}
}
我是 运行 Symfony 3 LTS。
我有一个订阅者正在监听 postUpdate
事件,以便将我数据库中产品的所有 activity 登录到数据库。下面是我的代码:
use AppBundle\Entity\History;
public function getSubscribedEvents()
{
return [
Events::postUpdate,
];
}
public function postUpdate(LifecycleEventArgs $args)
{
if(!is_null($this->tokenStorage->getToken())) {
$user = $this->tokenStorage->getToken()->getUser();
$entity = $args->getObject();
$em = $args->getEntityManager();
if ($entity instanceof Product) {
$history = new History($user, "Product #5 has been updated");
$em->persist($history);
}
$em->flush();
}
}
问题:History
在数据库中插入了两次。我不知道为什么。我试图删除 persist()
and/or flush()
方法,但没有创建任何内容。
PS:我的实体 Product
和 History
之间没有关系。它一定不会。我的问题只是重复行为。
我没有正确答案,但有一个解决方法:
use AppBundle\Entity\History;
// Will contains the User ID to avoid duplicate log
private $flushed = [];
public function getSubscribedEvents()
{
return [
Events::postUpdate,
];
}
public function postUpdate(LifecycleEventArgs $args)
{
if(!is_null($this->tokenStorage->getToken())) {
$user = $this->tokenStorage->getToken()->getUser();
$entity = $args->getObject();
$em = $args->getEntityManager();
// Check that the User.id is not already created in History during the update PHP Process
if ($entity instanceof Product && !in_array($user->getId(), $this->flushed)) {
$history = new History($user, "Product #5 has been updated");
$em->persist($history);
// Add the user ID in our array to avoid duplicate
$this->flushed[] = $user->getId();
}
$em->flush();
}
}