Joe Scotto
Joe Scotto

Reputation: 10857

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.

Upvotes: 8

Views: 4573

Answers (4)

Jiyu
Jiyu

Reputation: 11

I am using regex to do this trick:

$app->get('/{router:login|sign-in}', function ($request, $response, $args) {
  echo "Hello, " . $args['router'];
});

Upvotes: 0

Rob Allen
Rob Allen

Reputation: 12778

FastRoute doesn't do what you want, however, you can use a parameter that is limited via regex to the list of urls that you want to use:

$app->get("/{_:sign-in|login}", function ($request, $response) {
    $response->write("Hello!");
    return $response;
});

Note that you have to have an argument name, so I've use _ as it's inoffensive.

Upvotes: 1

Steve
Steve

Reputation: 20459

Just create the function as a closure and pass it as a parameter:

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

$app->get('/sign-in', $home);

$app->get('/login',   $home);

Or use a named function:

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

$app->get('/login',   'home');

Upvotes: 3

Joe Scotto
Joe Scotto

Reputation: 10857

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');
    });
}

Upvotes: 4

Related Questions