我正在尝试创建一个导致两个响应的控制器操作。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');
}
}