Symfony请求在EventSubscriber中不可用

时间:2019-04-12 21:15:53

标签: symfony

使用Doctrine生命周期事件的EventSubscriber记录对我的实体的更改。我想在实体更改日志条目旁边记录一个请求ID,以查看单个用户操作中发生了什么。

添加请求ID很简单:

class RequestIdSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents(): array
    {
        return [KernelEvents::REQUEST => 'addRequestId'];
    }

    public function addRequestId(GetResponseEvent $event): void
    {
        $request = $event->getRequest();
        $request->attributes->set('RequestId', Uuid::uuid1()->toString());
    }
}

问题在于该请求似乎在Doctrine EventSubscribers中似乎不可靠:

class EntityEventSubscriber implements EventSubscriber
{
    public function __construct(DelayedEventDispatcher $dispatcher, RequestStack $requestStack, LoggerInterface $logger)
    {
        $this->dispatcher = $dispatcher;
        $this->inventory = new EntityInventory();
        $this->requestStack = $requestStack;
        $this->logger = $logger;
    }

    public function getSubscribedEvents(): array
    {
        return [
            Events::postUpdate,
        ];
    }

    public function postUpdate(LifecycleEventArgs $args): void
    {
        // works
        $this->logger->debug($this->requestStack->getCurrentRequest()->get('RequestId')); 

        $entity = $args->getEntity();
        $changes = $this->inventory->getChangeSet($entity);
        $event = new EntityUpdatedEvent($entity, $changes);

        $this->triggerAuditLogEvent($event);
    }

    public function triggerAuditLogEvent(EntityEvent $event): void
    {
        // request.CRITICAL: Uncaught PHP Exception Error: "Call to a member function get() on null"
        $event->setRequestId($this->requestStack->getCurrentRequest()->get('RequestId')); 
        $this->dispatcher->dispatch(FhrEvents::GENERIC_ENTITY_EVENT, $event);
    }
}

所以真正困扰我的是,该请求似乎在一种方法中可用,如果我调用下一个方法,则该请求已经消失了。

0 个答案:

没有答案