Search code examples
phpsymfonysymfony-routingsymfony6

Named Routes in Symfony 6 with controllers in inner directory


I moved all my controllers to /src/Web/Controller in my Symfony 6 project like follows

├── src
│   ├── ...
│   └── Web
│   |    ├── Controller
│   |    ├── ....
|   |── Kernel.php

my routes.yaml is modified accordingly

#routes.yaml
controllers:
    resource: ../src/Web/Controller/
    type: annotation

Now the problem is all my routes have a name which is prefixed with app_web. Which due to this structure I suppose.

$ php bin/console debug:router command outputs following:

...
...
app_web_post_index    GET|HEAD        ANY      ANY    /post/             
app_web_post_create   GET|HEAD|POST   ANY      ANY    /post/create 

Here I only want the name to be post_index How do I get rid of this prefix?


Solution

  • If you do not name the routes explicitly, they are named for you.

    The names are generated using the fully qualified name for the class and method for the controller (although without the last part of the namespace —controller—, for some reason).

    If you do not want to use the auto-generated names, simply name your routes yourself:

    #[Route('/post')]
    class Post
    {
        #[Route(path: '/', name: 'post_index', methods: ['HEAD', 'GET'])]
        public function index(Request $request): Response
        {
            return new Response('post index');
        }
    
        #[Route(path: '/create', name: 'post_create', methods: ['HEAD', 'GET', 'POST'])]
        public function create(Request $request): Response
        {
            return new Response('post create');
        }
    }
    

    With the built-in options you can add a prefix to a group of routes, but not remove it from the auto-generated name.

    If this is really important for your use case to happen "automatically", I guess you could build your own route loader, but I'd say it is overkill for this. Just name the routes appropriately, or live with the auto-generated name.


    Naming the routes explicitly is generally a better idea/practice, because if you refer to the route names anywhere else you'd be guaranteed of the names remaining the same even if you chose to refactor your controllers to a different code structure.