BerlinElle
BerlinElle

Reputation: 15

2 Symfony routes with the same pattern, how to?

I am stuck in one issue and cannot get out of it.

I have 2 urls that look the same but should route to different controllers.

  1. mysite.com/{alias} => will take to mysite.com/contact ; mysite.com/about...etc Controller: AppBundle:Default:page.html.twig

  2. mysite.com/{alias} => will to take a list of shops I have in my database. Examples: mysite.com/ebay ; mysite.com/apple...etc Controller: AppBundle:Shop:index.html.twig

How would you do that?

Thanks in advance

Upvotes: 0

Views: 858

Answers (1)

Terenoth
Terenoth

Reputation: 2598

Using the same pattern is not a good idea, since Symfony will try to match all your routes one by one, in the order you defined in your routing.yml. So your second pattern will always be ignored when the first will be matched.

I advise you to be more accurate on your patterns: you should have exact patterns for your static pages (/contact, /about, etc.) and have a controller action for each. If you don't want, you can define several @Route annotation on a single action, or define requirements to a single @Route annotation. (like @Route("/{alias}", requirements={"alias"="(contact|about)"})

Then, you can have a fallback pattern /{alias} for the list of shops.

EDIT: The aim is, instead of having a single Regex to match all your cases, to have several of them, but with the same behaviour that you already have.

If you define routing this way (in this exact order):

1. /contact => Contact action
2. /about => About action
3. /{alias} => Shop action (matches every other URL than /contact and /about, like /amazon, /ebay, etc.)

Then this should work as you intend.

If the user visits yoursite.com/contact, the first pattern will match, thus the user will see the contact page.

If the user visits yoursite.com/about, the first pattern will fail but the second will match, thus the user will see the about page.

If the user visits yoursite.com/ebay, the first and second patterns will fail but the third will match, thus the user will see the shop page associated to the "ebay" slug.

Upvotes: 3

Related Questions