пытается сделать подписчика для действий сущности (CRUD) и не может понять это.
Я знаю, что есть способ сделать слушателя и отправить ему 3 разных события, но это не то, чего я хочу достичь, я даже не думаю, что это хорошее решение.
Подписчик на мероприятие
<?php
namespace App\EventListener;
use App\Entity\Log;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Events;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
/**
* Part of program created by David Jungman
* @author David Jungman <[email protected]>
*/
class EntitySubscriber implements EventSubscriberInterface
{
/**
* @var EntityManagerInterface
*/
private $em;
/**
* @var TokenStorageInterface
*/
private $tokenStorage;
public function __construct(TokenStorageInterface $tokenStorage, EntityManagerInterface $em)
{
$this->em = $em;
$this->tokenStorage = $tokenStorage;
}
public static function getSubscribedEvents()
{
return array(
Events::postPersist,
Events::postUpdate,
Events::postRemove,
);
}
public function postUpdate(LifecycleEventArgs $args)
{
$this->logEvent($args, "remove");
}
public function postRemove(LifecycleEventArgs $args)
{
$this->logEvent($args, "remove");
}
public function postPersist(LifecycleEventArgs $args)
{
$this->logEvent($args, "create");
}
private function logEvent(LifecycleEventArgs $args, string $method)
{
$entity = $args->getEntity();
if ($entity->getShortName() != "Log")
{
$user = $this->tokenStorage->getToken()->getUser();
$log = new Log();
$log
->setUser($user)
->setAffectedTable($entity->getShortName())
->setAffectedItem($entity->getId())
->setAction($method)
->setCreatedAt();
$this->em->persist($log);
$this->em->flush();
}
}
}
и моя часть Service.yaml
App\EventListener\EntitySubscriber:
tags:
- { name: doctrine.event_subscriber, connection: default }
Я пытался:
Я просмотрел эти 2 официальных руководства: -https://symfony.com/doc/current/event_dispatcher.html -https://symfony.com/doc/current/doctrine/event_listeners_subscribers.html
но ничего не помогло .. когда я использую показанную часть конфигурации, мой компьютер зависает.
Когда я пытаюсь отладить его, я вижу, что эти методы активны (php bin / отладка консоли: диспетчер событий)
но они слушают событие "событие"






В Doctrine есть собственная система обработчик событий / подписчик. Однако с классом Symfony\Component\EventDispatcher\EventSubscriberInterface;, который вы реализуете, это из системы событий Symfony.
<?php
use Doctrine\ORM\Events;
use Doctrine\Common\EventSubscriber; // **the Doctrine Event subscriber interface**
use Doctrine\Common\Persistence\Event\LifecycleEventArgs;
class MyEventSubscriber implements EventSubscriber
{
public function getSubscribedEvents()
{
return array(
Events::postUpdate,
);
}
public function postUpdate(LifecycleEventArgs $args)
{
$entity = $args->getObject();
$entityManager = $args->getObjectManager();
// perhaps you only want to act on some "Product" entity
if ($entity instanceof Product) {
// do something with the Product
}
}
}