New in Symfony 2.6: New shortcut methods for controllers
September 25, 2014
•
Published by
Javier Eguiluz
Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.
Symfony comes with a very handy base Controller class that assists with some
of the most common controller tasks. When your controllers extend from the
Symfony
class, you can take
advantage of several helper methods, such as redirect()
, getUser()
and
createNotFoundException()
.
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.6
return $this->redirectToRoute('homepage');
return $this->redirectToRoute('product_show', array('id' => 12), 301);
// Previous Symfony versions
return $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.6
if ($this->isGranted('ROLE_ADMIN')) {
// ...
}
// Previous Symfony versions
if ($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 versions
if (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 versions
use Symfony\Component\Security\Csrf\CsrfToken;
$this->get('security.csrf.token_manager')->isTokenValid(new CsrfToken('token_id', 'TOKEN'))
Help the Symfony project!
As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.
Thanks to the contributor and the DX initiative.
Thanks to the DX initiative
but thank you :)