5 Shortcuts method that will save you precious typing time !

5 Shortcuts methods for Symfony2 controllers that probably you didn't know they existed

With the quick publication of Symfony 2.6 which count with more than 100 new features and enhancementes to the famous framework (and of course we will not discuss in this article).

The following group of functions are only shortcuts that will save you some typing time, use the old way IS NOT DEPRECATED (unless not yet ...) because they use the same component and the news method are included in the Controller Class.

If your controllers extend from the Symfony\Bundle\FrameworkBundle\Controller\Controller you are allowed to use :

redirectToRoute

This function allows you to return a redirection based on the name of the route instead of having to generate first the URL like in previous versions.

// 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);

addFlash

Quickly way to create a flash message of the given type (error,info etc ..), checking first if the user session is available:

// 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.');

isGranted

isGranted checks if the given attributes of the user (Role hierarchy) are granted against the current authentication token and the optionally supplied object:

// Symfony 2.6
if ($this->isGranted('ROLE_ADMIN')) {
    // ...
}
// Previous Symfony versions
if ($this->get('security.context')->isGranted('ROLE_ADMIN')) {
    // ...
}

denyAccessUnlessGranted

Throws an exception unless the attributes are granted against the current authentication token and the optionally supplied object ( 403 forbidden ):

// 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.');
}

isCsrfTokenValid

This shortcut checks the integrity of the given CSRF token (forms validation and other session purposes):

// 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'))

Primary source : http://symfony.com/blog/new-in-symfony-2-6-new-shortcut-methods-for-controllers


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors