symfony2 use multiple url pattern for a single Con

2020-02-09 08:53发布

问题:

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

回答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+


回答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



回答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}) }}