Optional route prefix

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:

  1. Is there a more elegant way to implement the optional route prefix?

  2. Is there a way to access route parameters inside a group handler but outside a route definition?

Thanks!

Why not just generate 2 (or however many you need) versions of the same route. That way you don’t have to modify REQUEST_URI and can just define the routes as you need them. Seems like a cleaner approach …

Multiple versions of every route would mean duplicating hundreds of routes, I don’t think that is very elegant. It’d not be an issue if all URLs had the API version in them because then I can just match the newer versions first and then at the end have a match all (like in my example above) for those APIs that have not changed.

The difficulty is that I have existing clients that use the API without specifying the API version as part of the URL. Those I need to continue to support and want to map them to current version of the API.

I believe patching REQUEST_URI is probably the best thing to do here. Was just looking for something more along the Slim way of doing things.