Skip to content

Instantly share code, notes, and snippets.

@immutef
Created December 22, 2011 15:21
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save immutef/1510669 to your computer and use it in GitHub Desktop.
Save immutef/1510669 to your computer and use it in GitHub Desktop.
[Symfony2] example usage of streamed response and post response code execution
<?php
/*
* Example usage of streamed response and post response code execution.
*
* @author Pierre Minnieur <pierre.minnieur@sensiolabs.de>
*
* @see https://github.com/symfony/symfony/pull/2791
* @see https://github.com/symfony/symfony/pull/2935
* @see https://github.com/sensio/SensioFrameworkExtraBundle/pull/86
*/
namespace Acme\DemoBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpKernel\Event\PostResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Doctrine\ORM\ORMException;
use Acme\DemoBundle\Entity\User;
use Acme\DemoBundle\Form\Type\UserType;
class UserController extends Controller
{
/**
* @Route("/user/register")
* @Method({"GET", "POST"})
* @Template(streamable=true)
*/
public function registerAction()
{
$form = $this->createForm(new UserType(), new User());
if ($this->getRequest()->getMethod() == 'POST') {
$form->bindRequest($this->getRequest());
if ($form->isValid()) {
$user = $form->getData();
try {
$em = $this->getDoctrine()->getEntityManagerForClass('Acme\DemoBundle\Entity\User');
$em->persist($user);
$em->flush();
$this->get('session')->setFlash('success', 'user.register.success');
} catch (ORMException $e) {
$this->get('session')->setFlash('error', 'user.register.failure');
}
// post response code execution (mailer)
$this->get('event_dispatcher')->connect(
KernelEvents::TERMINATE,
function (PostResponseEvent $event) use ($user) {
$mailer = $event->getKernel()->getContainer()->get('mailer');
$message = \Swift_Message::newInstance();
// ... build your message
$mailer->send($message);
}
);
return $this->redirect($this->generateUrl('_demo'));
} else {
$this->get('session')->setFlash('warning', 'user.register.validation');
}
}
return array( // streamed response
'user' => $form->getData(),
'form' => $form->createView(),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment