Hello everyone!

We have been investing plenty of personal time and energy for many years to share our knowledge with you all. However, we now need your help to keep this blog running. All you have to do is just click one of the adverts on the site, otherwise it will sadly be taken down due to hosting etc. costs. Thank you.

If you're using requirements property of @Route annotation for your controllers, maintaining requirement rules can be very hard, especially if you are duplicating same rule for many controllers and methods. The solution follows as follows.


Problematic controller


If you ever had to change guid regex pattern below and used it in many other places, you would have an headache. You know why!


namespace Application\FrontendBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Response;

/**
* @Route("", service="application_frontend.controller.user")
*/
class UserController extends Controller
{
/**
* @param string $guid
*
* @Route("/user/{guid}", requirements={"guid"="([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}"})
* @Method({"GET"})
*
* @return Response
*/
public function getUserAction($guid)
{
// Do something with $guid
}
}

Clean controller


namespace Application\FrontendBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Response;
use Application\FrontendBundle\Validator\GuidAnnotation;

/**
* @Route("", service="application_frontend.controller.user")
*/
class UserController extends Controller
{
/**
* @param string $guid
*
* @Route("/user/{guid}", requirements={"guid"=GuidAnnotation::PATTERN})
* @Method({"GET"})
*
* @return Response
*/
public function getUserAction($guid)
{
// Do something with $guid
}
}

GuidAnnotation class


namespace Application\FrontendBundle\Validator;

class GuidAnnotation
{
const PATTERN = '([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}';
}