Symfony2:控制器产生两个响应


Symfony2: controller results in two responses

>我正在尝试创建一个导致两个响应的控制器操作。 SwiftMailer 使用 kernel.terminate 事件来实现此目的。 我可以为事件构建一个事件侦听器,但我不知道如何告诉它我希望它做什么。 我知道创建和下载 pdf 文件需要什么,但听众如何知道何时执行此操作?

编辑:

"告诉它"在SO中通过这样做找到:

    if ($nextAction) {
        $request->attributes->set('household_id', $id);
    }

但是根本不清楚如何让事件侦听器完成所有这些操作(从控制器复制,但对于第一行):

$em = $this->container->get('doctrine.orm.default_entity_manager');
$household = $em->getRepository('ManaClientBundle:Household')->find($id);
$fname = $household->getHead()->getFname();
$sname = $household->getHead()->getSname();
$filename = $sname . $fname . 'card.pdf';
$stylesheetXml = $this->renderView('ManaClientBundle:Test:pdfstyle.xml.twig', array());
$facade = $this->get('ps_pdf.facade');
$response = new Response();
$this->render('ManaClientBundle:Test:card.pdf.twig', array(
    'household' => $household,
    'date' => date_create(),
        ), $response);
$xml = $response->getContent();
$content = $facade->render($xml, $stylesheetXml);
header('content-type:application/pdf;' .
        'Content-Disposition:attachment; filename=' . $filename);
echo $content;

表格包括:

->add('save', 'submit')
->add('saveCreate', 'submit')

控制器包括:

$nextAction = $form->get('saveCreate')->isClicked();
if ($nextAction) {
// tell event to create and download a pdf file using $id
}
return $this->redirect($this->generateUrl('household_show', array('id' => $id)));

服务:

  listener.pdfresponse:
    class: Mana'ClientBundle'EventListener'PdfListenerSubscriber
    arguments: [ @service_container ]
    tags:
      - { name: kernel.event_listener, event: kernel.terminate, method: onKernelTerminate }

听者

namespace Mana'ClientBundle'EventListener;
use Symfony'Component'DependencyInjection'ContainerInterface;
use Symfony'Component'HttpKernel'Event'PostResponseEvent;
use Symfony'Component'HttpKernel'KernelEvents;
use Symfony'Component'EventDispatcher'EventSubscriberInterface;
class PdfListenerSubscriber implements EventSubscriberInterface {
     private $container;
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }
    public function onKernelTerminate(PostResponseEvent $event) {
        //create and download pdf file
    }
    static public function getSubscribedEvents()
    {
        return array(
            KernelEvents::TERMINATE => 'onKernelTerminate');
    }
}

对HTTP请求的两个响应是不可能的 - 一旦第一个请求得到响应,Web服务器就会断开连接,因此第二个响应将无处发送。