0

I am coding an API to improve my personnal PHP skills. I have a problem with 2 routes :

recette.recetteById:
   path: /api/recette/{id}
   controller: App\Controller\RecetteController::recetteById

recette.subRecette:
  path: /api/recette/sub-recette
  controller: App\Controller\RecetteController::subRecette

When I go to /api/recette/sub-recette it shows me the return of my recetteById function instead of subRecette, it seems that /sub-recette is used as /{id}.

My recetteById is just a function that returns the id as json, so when I go to /api/recette/sub-recette it show sub-recette. Why the route doesn't call my subRecette function?

What do I have to do to call subRecette function when I go /api/recette/sub-recette

recetteByID :

public function recetteById($id) {
  return $this->json($id);
}
2
  • That dot in route names really strikes my eye. Can you try replacing it with _? Commented Dec 1, 2022 at 10:12
  • i can't it it must be name "sub-recette" Commented Dec 1, 2022 at 10:20

1 Answer 1

1

After editing the question and reading it more closely, I see what the issue is.

The routing works by the principle first match wins. To it, the sub-recette looks a lot like a perfectly valid ID.

In order to circumvent this, if your ID is, say, number, you could do:

recette.recetteById:
    path: /api/recette/{id}
    requirements: 
        id: '\d+'
    controller: App\Controller\RecetteController::recetteById

Another way to achieve this is to put subRecette before recetteById but this is error-prone.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer, it works :), and thanks for the editing too. By the way, what is an "error-prone" if i place subRecette before recetteById
You let the order or routes dictate the validity. Inevitably, in some projects, you will make mistake and put some routes in the wrong order, causing an error :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.