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}';
}