symfony2 use multiple url pattern for a single Controller Action using regular expression

34,190

Solution 1

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+

Solution 2

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

Solution 3

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}) }}
Share:
34,190
svassr
Author by

svassr

Updated on July 13, 2020

Comments

  • svassr
    svassr almost 4 years

    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

  • svassr
    svassr almost 12 years
    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
    cvaldemar almost 12 years
    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
    Wirone over 9 years
    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")).
  • Kamil Latosinski
    Kamil Latosinski over 6 years
    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?