Contributed by
Thomas Royer
in #11593.
andGrégoire Pineau
in #11602.
Symfony comes with a very handy base Controller class that assists with some
of the most common controller tasks. When your controllers extend from theSymfony\Bundle\FrameworkBundle\Controller\Controller
class, you can take
advantage of several helper methods, such as redirect()
, getUser()
andcreateNotFoundException()
.
These helpers are so useful, that we've decided to include five new controller helpers in Symfony 2.6 to boost your productivity:
1.redirectToRoute()
, allows to return a redirection based on the name
of the route instead of having to generate first the URL:
1 2 3 4 5 6 7 8 9 | // Symfony 2.6return$this->redirectToRoute('homepage');return$this->redirectToRoute('product_show',array('id'=>12),301);// Previous Symfony versionsreturn$this->redirect($this->generateUrl('homepage'));return$this->redirect($this->generateUrl('product_show',array('id'=>12)),301); |
2.addFlash()
, allows to create a flash message of the given type, checking
first if the user session is available:
1 2 3 4 5 | // Symfony 2.6$this->addFlash('info','The item was created successfully.');// Previous Symfony versions$this->get('session')->getFlashBag()->add('info','The item was created successfully.'); |
3.isGranted()
, checks if the given attributes are granted against the
current authentication token and the optionally supplied object:
1 2 3 4 5 6 7 8 9 | // Symfony 2.6if($this->isGranted('ROLE_ADMIN')){// ...}// Previous Symfony versionsif($this->get('security.context')->isGranted('ROLE_ADMIN')){// ...} |
4.denyAccessUnlessGranted()
, throws an exception unless the attributes
are granted against the current authentication token and the optionally supplied
object:
1 2 3 4 5 6 7 | // Symfony 2.6$this->denyAccessUnlessGranted('ROLE_EDIT',$item,'You cannot edit this item.');// Previous Symfony versionsif(false===$this->get('security.context')->isGranted('ROLE_EDIT',$item)){throw$this->createAccessDeniedException('You cannot edit this item.');} |
5.isCsrfTokenValid()
, checks the validity of the given CSRF token:
1 2 3 4 5 6 7 | // Symfony 2.6$this->isCsrfTokenValid('token_id','TOKEN');// Previous Symfony versionsuseSymfony\Component\Security\Csrf\CsrfToken;$this->get('security.csrf.token_manager')->isTokenValid(newCsrfToken('token_id','TOKEN')) |