Is that possible with symfony2 to define multiple url patterns for a single Controller Action using regular expressions, so we don't have to define several rules ? Thanks in advance
3 Answers
When using annotations, you can define multiple routes. Like that:
/**
* @Route ("item1")
* @Route ("item/2")
* @Method("GET")
*/
public function itemAction() {
}
I'm using Version 2.0.9
3 Comments
svassr
That's really interesting, I like the idea of having the related routings defined just before an Action, but I'd prefer to keep everything in only one routing.yml instead of spreading my routing rules in all my controllers
cvaldemar
As you probably have the app/console open, don't forget the router:debug command to see all your routes. If you use annotations, you'll get sensible names for your routes by default, so it's actually quite easy to find the controller.
Wirone
It's not possible to keep all routes in one file when you use multiple bundles (when you include routes as resource in main app
routing.yml), so this is not really an argument for routing. Annotations are easy to use, easy debugable (router:debug) and configurable (you can set your own name for example: @Route ("/", name = "homepage")).Do you mean placeholders with requirements?
blog:
pattern: /blog/{page}
defaults: { _controller: AcmeBlogBundle:Blog:index, page: 1 }
requirements:
page: \d+
Here you have multiple routes defined by a placeholder, validated by regular expressions going to the same controller action.
Edit:
Each part of the url can be a placeholder.
blog:
pattern: /{type}/{page}
defaults: { _controller: AcmeBlogBundle:Blog:index, page: 1 }
requirements:
type: blog|articles
page: \d+
1 Comment
Kamil Latosinski
what if I want to have type omittable? For example how would you define a route for:
/posts/sport/2, posts/sport, posts/2. So the generic route is: /posts/{category}/{page}, but - obviously - it doesn't work with only default values. Is there any way to tell symfony how to recognize if second param is string/int?Annotations example for routes with parameters :
/**
* @Route("/shops/{page}", name="shops")
* @Route("/shops/town/{town}/{page}", name="shops_town")
* @Route("/shops/department/{department}/{page}", name="shops_department")
*/
public function shopsAction(Town $town = null, Department $department = null, $page = 1)
{ ... }
Then generate route in twig like this :
{{ path('shops_town') }}
or
{{ path('shops_town', {'town': town.id}) }}
or
{{ path('shops_department', {'department': department.id}) }}
1 Comment
user878812
Hello, are you sure about the first statement to generate an url, shouldn't it be path('shops') rather than path('shops_town') ?