I have an extensive Slim v3 API where I want to introduce an optional version prefix to all my routes.
Today I have e.g. /user/create
. This should remain valid but I now want the same routes to be reachable as /v1/user/create
. If the version prefix is not given, then it is automatically sets it to the current version.
After experimenting a bit, I reverted to modifying the $_SERVER["REQUEST_URI"]
before Slim does its parsing:
if (!preg_match('/^\/v\d+\.d+\//', $_SERVER["REQUEST_URI"]))
$_SERVER["REQUEST_URI"] = "v" . MAJOR_VERSION . "." . MINOR_VERSION . $_SERVER["REQUEST_URI"];
Then I have wrapped all my route definitions inside a new group:
$app->group('/v{api_major_version:\d+}.{api_minor_version:\d+}',
function()
{
// lots and lots of routes
}
This works well but I am not really proud of having to fiddle with the request before Slim takes care of it. The other problem I have is that I don’t have a good place to act on the version outside the individual routes. I’d like to do some generic sanity checking right inside the group but the group function does not get access to the arguments I believe. So my questions are:
-
Is there a more elegant way to implement the optional route prefix?
-
Is there a way to access route parameters inside a
group
handler but outside a route definition?
Thanks!