Symfony2:控制器产生两个响应

时间:2013-10-04 20:33:45

标签: php symfony

我正在尝试创建一个导致两个响应的控制器操作。 SwiftMailer使用kernel.terminate事件来完成此任务。我可以为事件构建一个事件监听器,但我不知道如何告诉它我想要它做什么。我知道创建和下载pdf文件需要什么,但是听众如何知道何时这样做?

编辑:

“告诉它”是found here in 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');
    }
}

1 个答案:

答案 0 :(得分:1)

对HTTP请求的两个响应永远不可能 - 一旦响应了第一个请求,Web服务器就会删除连接,因此无法发送第二个响应。