使用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
- 用例:显式持久化(新创建的)