如何在服务中使用kernel.terminate事件

mpi*_*iot 3 symfony symfony-3.2

我做了一项运行繁重任务的服务,这个服务是在Controller中调用的.为了避免过长的页面加载,我希望返回HTTP响应并在之后运行繁重的任务.

我读过我们可以使用kernel.terminate事件来做,但我不明白如何使用它.

目前我尝试在KernelEvent上执行一个监听器:TERMINATE,但我不知道如何过滤,因为监听器只在好页面上执行作业...

是否可以在触发事件时添加要执行的函数?然后在我的控制器中,我使用该函数添加我的动作,Symfony稍后执行它.

谢谢你的帮助.

mpi*_*iot 8

最后,我已经找到了如何做到这一点,我在我的服务中使用EventDispatcher,并在这里连接一个监听器PHP关闭:http://symfony.com/doc/current/components/event_dispatcher.html#connecting-listeners

use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpKernel\KernelEvents;

class MyService
{
  private $eventDispatcher;

  public function __construct(TokenGenerator $tokenGenerator, EventDispatcherInterface $eventDispatcher)
  {
   $this->tokenGenerator = $tokenGenerator;
   $this->eventDispatcher = $eventDispatcher;
  }

  public function createJob($query)
 {
    // Create a job token
    $token = $this->tokenGenerator->generateToken();

    // Add the job in database
    $job = new Job();
    $job->setName($token);
    $job->setQuery($query);

    // Persist the job in database
    $this->em->persist($job);
    $this->em->flush();

    // Call an event, to process the job in background
    $this->eventDispatcher->addListener(KernelEvents::TERMINATE, function (Event $event) use ($job) {
        // Launch the job
        $this->launchJob($job);
    });

    return $job;
 }
Run Code Online (Sandbox Code Playgroud)

  • 在该示例中,这是一个服务,当您调用服务并使用`createJob`方法时,您会在`KernelEvents :: TERMINATE`上添加一个侦听器,但仅针对此`Response`。当用户加载另一个页面时,`KernelEvents :: TERMINATE`上没有侦听器。 (2认同)