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条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度