Contributed by
Thomas Royer in #11593. and Gré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 the Symfony\Bundle\FrameworkBundle\Controller\Controller 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'))