Reputation: 637
I am working on a REST API project using Slim 3, and I was wondering if there is an easy way to implement the following routing without creating separate routes for the shorthands.
The shorthand is ../me
for ../users/{id}
where the id
is the current users ID.
So far its easy, I just create the two routes, and map them to the same controller method; but there are many more endpoints which use the same logic for example:
../users/{id}/posts
should use the same as ../me/posts
,
../users/{id}/groups/{gid}
should use the as ../me/groups/{gid}
, etc.
I used the double dots to indicate that there are preceding URI parts (version, language etc.). I hope you get the idea now.
So my question is this: is there a way to reroute these kind of requests, or maybe is there a route pattern that would fit my needs and i missed it, maybe even I have to fiddle in a middleware to achieve this?
Thanks
Upvotes: 0
Views: 556
Reputation: 435
There is a way to take advantage of Slim's FastRoute router. Put a regular expression into the variable part of your route and do the extra parsing inside the controller:
$app->get('/whatever/{id:users/\d+|me}', function ($request, $response, $args) {
if (preg_match('%^users/(\d+)$%', $args['id'], $parsed)) {
// This is /users/{id} route:
$user = $parsed[1];
} else {
// This is /me route:
$user = 'automagically recognized user';
}
return $response->withStatus(200)->write('Hello '.$user);
});
However I'd find that strange and would recommend mapping the same controller to two individual routes, as you do now. Two reasons come to my mind:
Hope it helps!
Upvotes: 1
Reputation: 1646
Try it
$app->get('/users[/{id}/groups[/{msgid}]]', function ($request, $response, $args) {
}
and see the oficial documentation in http://www.slimframework.com/docs/objects/router.html
Upvotes: 0