Symfony2 usa múltiples patrones de URL para una sola acción de controlador usando una expresión regular

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

preguntado el 03 de mayo de 12 a las 21:05

3 Respuestas

When using annotations, you can define multiple routes. Like that:

/**
 * @Route ("item1")
 * @Route ("item/2")
 * @Method("GET")
 */
public function itemAction() {

}

Estoy usando la versión 2.0.9

contestado el 08 de mayo de 12 a las 11:05

That's really interesting, I like the idea of having the related routings defined just before an Acción, but I'd prefer to keep everything in only one enrutamiento.yml instead of spreading my routing rules in all my controllers - svassr

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. - cvaldemar

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")). - Wirone

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+

contestado el 09 de mayo de 12 a las 07:05

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? - kamil latosinski

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

Respondido 12 Jul 16, 18:07

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.