symfony - Symfony (5.1) Doctrine Event Listener 被触发,但不是 Entity Listener
问题描述
使用Symfony 官方文档,我正在清理一些代码,并想在 Symfony 中替换一个 Doctrine 事件监听器(工作):
namespace App\EventListener;
use App\Entity\Comment;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class CommentAuthorAssignmentListener
{
private $tokenStorage;
public function __construct(TokenStorageInterface $tokenStorage)
{
$this->tokenStorage = $tokenStorage;
}
public function prePersist(Comment $comment, LifecycleEventArgs $event)
{
dump($comment, $event); exit;
$comment->setAuthor($this->tokenStorage->getToken()->getUser());
}
}
services:
App\EventListener\CommentAuthorAssignmentListener:
autowire: true
tags:
- { name: doctrine.event_listener, event: prePersist }
使用更具体的实体侦听器(没有错误但根本没有启动):
namespace App\EventListener;
use App\Entity\Comment;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class CommentAuthorAssignmentListener
{
private $tokenStorage;
public function __construct(TokenStorageInterface $tokenStorage)
{
$this->tokenStorage = $tokenStorage;
}
public function prePersist(Comment $comment, LifecycleEventArgs $event)
{
$comment->setAuthor($this->tokenStorage->getToken()->getUser());
}
}
services:
App\EventListener\CommentAuthorAssignmentListener:
autowire: true
tags:
- { name: doctrine.entity_listener , entity: 'App\Entity\Comment', event: prePersist }
一些注意事项:
- 我确实跑了
cache:clear
- 用例:显式持久化(新创建的)
解决方案
看起来你打错了:
# these are the options required to define the entity listener
name: 'doctrine.orm.entity_listener'
event: 'postUpdate'
entity: 'App\Entity\User'
注意“.orm”。在标签名称中,因此对于您的用例:
services:
App\EventListener\CommentAuthorAssignmentListener:
autowire: true
tags:
- { name: doctrine.orm.entity_listener , entity: 'App\Entity\Comment', event: prePersist }
推荐阅读
- angular - 添加自定义角度复选框
- python-3.x - 如何在不使用python中的find()方法的情况下在另一个字符串中查找一个字符串
- python - 我如何同时运行具有不同输入的一个功能?
- python - 跨多列融合 DataFrame
- python - 如何按块读取存储在磁盘上的 LongTensor
- java - 通过 https 运行与 Geoserver 平台无关的二进制文件?
- reactjs - 如何在钩子中访问当前组件的顶级元素 ref?
- python - Python - Selenium:无法定位在框架内加载的元素
- python - 如何使用 Pandas 编辑系列的实例
- ibm-cloud - 如何阻止我的 Watson Assistant 自动更正用户输入