Routing order symfony 4

送分小仙女□ 提交于 2021-01-27 11:52:00

问题


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.


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/48494301/routing-order-symfony-4

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!