Symfony(5.1)主义事件侦听器被触发,但实体侦听器未触发

时间:2020-07-14 09:53:45

标签: symfony doctrine-orm symfony5 symfony-eventdispatcher

使用Symfony official documentation, 我正在清理一些代码,并想替换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 }

使用更具体的Entity侦听器(没有错误,但根本没有触发):

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
  • 使用案例:明确保留(新创建的)评论

1 个答案:

答案 0 :(得分:1)

您好像打错了字

 # 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 }
相关问题