Cruz Cruz - 23 days ago 7
PHP Question

Symfony 2 : Route requirements correct usage

Using Symfony 2, I wonder if the following usage of route requirements is correct or should it be dedicated to specific regular expressions ?

#routing.yml

fbn_guide_articles:
path: /{articles}
defaults: { _controller: FBNGuideBundle:Guide:articles }
requirements :
articles : infos|restaurants|winemakers|events|tutorials|shops


An alternative could be the following at controller level:

#routing.yml

fbn_guide_articles:
path: /{articles}
defaults: { _controller: FBNGuideBundle:Guide:articles }


class GuideController extends Controller
{
private static $articlesEntities = array(
'infos' => 'Info',
'restaurants' => 'Restaurant',
'winemakers' => 'Winemaker',
'events' => 'Event',
'tutorials' => 'Tutorial',
'shops' => 'Shop',
);

public function articlesAction($articles)
{
if (!array_key_exists($articles, self::$articlesEntities)) {
throw $this->createNotFoundException();
}

// Do the stuff
}
}


Thanks.

Answer

Requirements of a route is a more "declarative" way to do the same things, but that works early than controller action.

So, it's a fine solution if logic of your routing not too complex. In this case, implementation of same process in the controller is just a duplication of the framework functions that already tested and work fine.