Darius
Darius

Reputation: 1664

Routing order symfony 4

I want to have a url with a wildcard at the end site.com/{username} after trying to match url's like site.com/photos and site.com/blog. I'm using annotations and have two controllers.

I found an answer here Ordering of routes using annotations

But the folder structure is different in version 4 and in the answer they are using YAML while I'm using annotations, so I don't fully understand where to put what.

Video Controller

    /**
     * @Route("/videos", name="videos")
     */
    public function index()
    {
      // Show video homepage
    }

User Controller

    /**
     * @Route("/{username}", name="profile")
     */
    public function index()
    {
        // Hello {username} !
    }

In this order, site.com/videos reaches User controller instead of videos. Do I have to switch to manually putting all URL structures in yaml format or is there a way to set priority in annotations?

So far the only method I found was to create a controller starting with the letter "Z", and putting the action/route in there, that seems to run the route last.

Upvotes: 5

Views: 4938

Answers (3)

Anton Kolenkov
Anton Kolenkov

Reputation: 340

With current(6.2) version of Symfony you can (re)define route priority. Example from docs:

#[Route('/blog/list', name: 'blog_list', priority: 2)]

Bigger value, higher priority.

In your case it would be:

    /**
     * @Route("/videos", name="videos", priority: 2)
     */
    public function index()
    {
      // Show video homepage
    }

See documentation.

Upvotes: 1

Matias Kinnunen
Matias Kinnunen

Reputation: 8540

The question you linked to is actually very relevant. You are asking just the same as the other guy:

But how can you do this if you define your routes as annotations in your controllers? Is there any way to specify the ordering of this routes in this case?

In Symfony 4, your config/routes.yaml is probably empty and config/routes/annotations.yaml probably like this:

controllers:
    resource: ../../src/Controller/
    type: annotation

You can replace the above YAML with this – notice that the order does matter:

Video:
    resource: App\Controller\VideoController
    type: annotation

User:
    resource: App\Controller\UserController
    type: annotation

Then site.com/videos reaches the video controller first.

Upvotes: 5

goto
goto

Reputation: 8164

You have to define your routes with yml/xml to be able to fully configure their order.
If you really want to use annotation you could add a prefix like user-:

/**
 * @Route("/user-{username}", name="profile")
 */
public function index()
{
    // Hello {username} !
}

Upvotes: 1

Related Questions