hi all
i wanted to ask if there is a way to add prefix to all the routes.
for example i have to routes:
$app->get(’/users/{id}’,‘UserController:getUser’);
$app->get(’/users’,‘UserController:getUsers’);
so i want the route will actualy be:
/api/users/11
/api/users
is there a way to achieve this without adding ‘/api/’ to all the routes?
thanks
dudi
I would suggest that you define a variable $prefix which you conditionally set to either “/api” or to an empty string. That way you can do the following, depending on your exact needs:
$app->get("$prefix/users/{id}",'UserController:getUser');
Seems like an easy solution. You can then add a switch to your settings.php to configure the contents of $prefix at the beginning of your routes.php.
You can actually use $app->group($path, $callable) to achieve this. Inside the callable, you can treat $this like $app outside the callable. So you could revise your example to:
$app->group('/users', function() {
$this->get('/{id}', 'UserController:getUser');
$this->get('', 'UserController:getUsers');
});
Yep.
$app->group('/api', function () {
$this->get('/users/{id}','UserController:getUser');
$this->get('/users','UserController:getUsers');
});
The code above will result in /api/user/{id}
and /api/users