Symfony - 在Controller和EventListener之间共享数据

I'm currently using Symfony 3.4 as a stateless API, with Doctrine as an ORM. My controller loads some object from the database, does something with it, and returns a response. I have an EventListener registered for the kernel.terminate event to do post-processing after the response is sent - sending emails, etc. I'd like to have a mechanism to share objects loaded by the Controller with the EventListener, such that I don't have to do an extra database lookup in the EventListener.

Right now it looks something like this:

// Controller.php
public function fooAction(Request $request) {
   $id = $request->query->get('id');
   $bar = $this->databaseLookupBar($id);
   // do stuff to bar ...
   return new Response();
}

// EventListener.php
public function onKernelTerminate($event) {
   $request = $event->getRequest();
   $id = $request->query->get('id');
   $bar = $this->databaseLookupBar($id);
   // post-processing, send emails, etc.
}

I can think of two solutions:

1) Do it the way I'm currently doing it (1 redundant database lookup).

2) Store the object in the session, then clear the session when I'm done with it.

Is there a better solution?

Add a property and a setter method to your event listener class:

// EventListener.php

private $bar;

public function setBar($bar)
{
    $this->bar = $bar;
}

public function onKernelTerminate($event)
{
    $bar = $this->bar;
    // post-processing, send emails, etc.
}

Then call the setter from your controller:

// Controller.php

use Namespace\For\EventListenerClass

public function fooAction(Request $request, EventListenerClass $eventListener)
{
    $id = $request->query->get('id');
    $bar = $this->databaseLookupBar($id);
    // do stuff to bar ...

    $eventListener->setBar($bar);

    return new Response();
}