Search code examples
phpsymfonysymfony-routing

Is there a way to use both dynamic and static path on one controller?


I'm creating a Symfony CMS by myself. I want to map paths like /login and /{slug} at the same time, but I don't know if it is possible.

I tried simply setting both of the paths in 2 different controllers, but that didn't seem to work.

/**
*@Route('/login', name='login')
*/
public function login(){}

/**
*@Route('/{slug}', name='dynamic-site')
*/
public function dynamicSite(){}

With the setup above, the second path is reached every single time. There is no way to visit login. I expected Symfony to first try finding hard-coded routes, but it seems like it doesn't work like that.


Solution

  • The routing tries to match routes one by one in the order of their definitions. So, you have to order your controllers. Probably you have

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

    You should add the "/login" before the "controllers" import

    login:
        controller: App\Controller\Login
        type: annotation
    
    

    The result should be

    # config/routes.yaml
    login:
        controller: App\Controller\Login
        type: annotation
    Slug:
        controller: App\Controller\Slug
        type: annotation
    

    Don't forget to change controller names according to your application!

    You may re-read the docs - https://symfony.com/doc/current/routing.html

    I, personally, prefer to use yaml, because the order is very explicit.

    You should test if it is possible to have both imports

    login:
        controller: App\Controller\Login
        type: annotation
    controllers:
        resource: '../src/Controller/'
        type: annotation
    

    You may get an error. If the error appear, then you will have to list all your controllers 1 by 1.