php – Symfony在发送响应后运行代码
我看了
this other question.我正在寻找一种方法来做那个问题的OP也想要的,那就是
continue processing php after sending http response,但是在Symfony2中.
我实现了一个在每次内核终止后触发的事件.到目前为止一切都那么好,但我想要的是它在CERTAIN终止后,在特定的控制器动作中触发,例如在发送表单之后,而不是每次请求时.那是因为我想在某些时候做一些繁重的任务,并且不希望最终用户等待页面加载. 不知道怎么能这样做? <?php namespace MedAppBundleEvent; use JMSDiExtraBundleAnnotationInjectParams; use JMSDiExtraBundleAnnotationService; use JMSDiExtraBundleAnnotationTag; use PsrLogLoggerInterface; use SymfonyComponentDependencyInjectionContainerInterface; use SymfonyComponentHttpKernelKernelEvents; use SymfonyComponentConsoleConsoleEvents; use SymfonyComponentEventDispatcherEventSubscriberInterface; use JMSDiExtraBundleAnnotationInject; /** * Class MedicListener * @package MedAppBundleEventListener * @Service("medapp_test.listener") * @Tag(name="kernel.event_subscriber") */ class TestListener implements EventSubscriberInterface { private $container; private $logger; /** * Constructor. * * @param ContainerInterface $container A ContainerInterface instance * @param LoggerInterface $logger A LoggerInterface instance * @InjectParams({ * "container" = @Inject("service_container"),* "logger" = @Inject("logger") * }) */ public function __construct(ContainerInterface $container,LoggerInterface $logger = null) { $this->container = $container; $this->logger = $logger; } public function onTerminate() { $this->logger->notice('fired'); } public static function getSubscribedEvents() { $listeners = array(KernelEvents::TERMINATE => 'onTerminate'); if (class_exists('SymfonyComponentConsoleConsoleEvents')) { $listeners[ConsoleEvents::TERMINATE] = 'onTerminate'; } return $listeners; } } 到目前为止,我已经将事件订阅到kernel.terminate一个,但显然这会在每次请求时触发它.我把它变成了Swiftmailer的EmailSenderListener 内核必须每次都听这个事件,即使它没有被触发也感觉有点奇怪.我宁愿只在需要时解雇它,但不知道该怎么做.
在onTerminate回调中,您将获得
PostResponseEvent的实例作为第一个参数.您可以从该对象获取请求以及响应.
然后,您应该能够决定是否要运行实际的终止代码. 您还可以将自定义数据存储在请求的属性包中.看到这个链接:Symfony and HTTP Fundamentals
您的代码可能如下所示: // ... class TestListener implements EventSubscriberInterface { // ... public function onTerminate(PostResponseEvent $event) { $request = $event->getRequest(); if ($request->attributes->get('_route') == 'some_route_name') { // do stuff } } // ... } 编辑: kernel.terminate事件旨在在发送响应后运行.但是symfony文档说的如下(摘自here):
编辑2: 要使用here中的解决方案,您可以直接编辑web / app.php文件以将其添加到那里(但这是某种“黑客核心”imo,即使它比以下更容易使用).或者你可以这样做: >向具有高优先级的kernel.request事件添加侦听器并启动输出缓冲(ob_start). 我没试过,但它确实应该有效. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- PHP连接Access数据库常见错误及解决方法
- PHP魔术方法的实际应用 – __get,__set和__call
- php生成复杂验证码(倾斜,正弦干扰线,黏贴,旋转)
- 从具有start-stop-daemon的LSB init脚本启动PHP守护程序
- php – .ics邀请日历不工作在outlook.com问题
- PHP 数组遍历方法大全(foreach,list,each)
- centos下file_put_contents()无法写入文件的原因及解决方法
- Codeigniter(CI)框架分页函数及相关知识
- php – jQuery ajax回到$_POST而不是REQUEST有效负载
- 如何在php循环中的每个第n项添加一个类(wordpress)