Используя Symfony официальную документацию , я очищал некоторый код и хотел заменить прослушиватель событий Doctrine в Symfony (рабочий):
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 }
с более конкретным c прослушивателем сущностей (без ошибок, но не запускается вообще):
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
- Пример использования: явно сохраняющийся (только что созданный) Комментарий