Search code examples
phprestslimslim-3

Slim 3 multiple routes to one function?


I've been looking all over online and can't find anything that tells you how to assign multiple routes to one callback. For example I want to move:

$app->get('/sign-in', function($request, $response) {
    return $this->view->render($response, 'home.twig');
});

$app->get('/login', function($request, $response) {
    return $this->view->render($response, 'home.twig');
});

into something like:

$app->get(['/sign-in', '/login'], function($request, $response) {
    return $this->view->render($response, 'home.twig');
});

Is there a way to do this with Slim 3? I found online that in Slim 2 you could use the conditions([]); function on the end to chain multiple routes to one callback.


Solution

  • It seems that you can simply define an array and loop through it to create multiple routes on one funciton.

    $routes = [
        '/',
        '/home', 
        '/sign-in',
        '/login',
        '/register',
        '/sign-up',
        '/contact'
    ];
    
    foreach ($routes as $route) {
        $app->get($route, function($request, $response) {
            return $this->view->render($response, 'home.twig');
        });
    }