duanbinian2243 2013-04-11 17:42
浏览 51
已采纳

Symfony2:为什么请求传递给受Symfony2中的AppCache影响的Kernel.Terminate EventListener

In my Symfony2.2 application I am using an onKernelTerminate EventListener so that I can do a piece of "heavy" processing after my response has been rendered so the user receives a faster response time.

In my controller I set an attribute on the request so that when the event listener runs, that attribute can be used to decide if there is something and what to process.

This works perfectly on my dev environment and on a test environment where AppCache is not enabled. But as soon as I enable AppCache (in my app.php) - which I want to do because I use it for all my HTTP caching - the event listener stops working because it seems the Request that I access via the Event in onKernelTerminate has an empty attributes parameter bag.

The attribute I set in the controller isn't available from the request in the PostResponseEvent.

Why does AppCache have this effect? And is there an alternative way to pass data between my controller and an Event Listener which would work with AppCache?

Here's a snippet of code so you can see:

#in my controller
$request->attributes->set('listener-to-process', 'test');


#in my EventListener:
public function onKernelTerminate(PostResponseEvent $event) {

    $request = $event->getRequest();

    //use this request attribute to decide what to process
    if (!$request->attributes->has('listener-to-process')) {
        return;
    };

    $type = $request->attributes->get('listener-to-process');
    $status = $this->api->persistTag(type);

    return;

}
  • 写回答

2条回答 默认 最新

  • dongshanni1611 2014-02-27 12:31
    关注

    I found the answer - and my confusion came from not knowing how to pass information between services in a single request. AppCache was a bit of a red-herring (though I still don't know why it resets changes to the request).

    I thought the only way was to set properties of the request so that the listening service could pull from the request. In fact services are persistent within the request - so the service itself can keep track of what it needs to do after the onKernelTerminate event.

    I created a private property of the service (eg $itemsToPersist) and during the course of the process add items to that array.

    Then in the listener onKernelTerminate method:

    $service = $this->container->get('your_service');
    $service->persistItems();
    

    just call the method which can loop through the itemsToPersist array and do whatever it needs to do.

    No need to pass stuff in the request!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类