【发布时间】:2018-01-24 15:30:52
【问题描述】:
我想在控制器返回响应后执行 symfony 函数。
我该怎么做?
这是我使用的所有类:
定义所有事件:这里我们在这个类中只定义了一个事件
<?php
# AcmeEvents.php
namespace test\apiBundle;
final class AcmeEvents
{
const AFTER_RETURN_RESPONSE = "acme.after_return_response";
}
定义监听器
<?php
#TestSubscriber.php
namespace test\apiBundle\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use test\apiBundle\AcmeEvents;
use Symfony\Component\Filesystem\Filesystem;
class TestSubscriber implements EventSubscriberInterface
{
public function __construct()
{
}
public static function getSubscribedEvents()
{
return array(
AcmeEvents::AFTER_RETURN_RESPONSE => 'processingFunction'
);
}
public function processingFunction(Event $event)
{
$fs = new Filesystem();
$fs->touch('files/myfile.json', 0700);
}
}
定义触发事件的控制器
<?php
#WelcomeController.php
namespace test\apiBundle\Controller;
#use all other components
use Symfony\Component\EventDispatcher\EventDispatcher;
use test\apiBundle\AcmeEvents;
class WelcomeController extends Controller
{
public function getWelcomeAction()
{
# all other processes
$event = new UploadEvent();
$dispatcher = new EventDispatcher();
$dispatcher->dispatch(
'AcmeEvents::AFTER_RETURN_RESPONSE', $event
);
return $response;
}
}
【问题讨论】:
-
您的服务定义是什么?
-
acme:类:test\apiBundle\EventListener\TestSubscriber 标签:-{ 名称:kernel.event_listener,事件:acme.after_return_response }
-
看看这个full example,看看在向客户端发送响应后如何执行一些事情(你必须监听
kernel.terminate事件)。 -
为什么你没有在 Action 中使用服务 event_dispatcher ? $this->get('event_dispatcher')->dispatch() .. 为什么是 new EventDispatcher() ??
-
@Mocrates 你为什么删除你的答案?看起来你有正确的解决方案。格式化可能需要一些工作。
标签: symfony events return dispatcher