Search code examples
phprestrouteslumendingo-api

Lumen/Dingo API Dynamic Versioning


I'm using Lumen for my project, currently the way I version my API is through prefixing and using a specific corresponding controller like so:

$api->get('/v1/users', 'App\Api\V1\Controllers\UserController@show');
$api->get('/v2/users', 'App\Api\V2\Controllers\UserController@show');

I want to change this, such that I take an argument from the user and use a controller based on that parameter.

This Route:
$api->get('/v{api_version}/users'...

Should use this controller: 
'App\Api\V{api_version}\Controllers\UserController@show'

I'm currently using Dingo along side Lumen, is there anyway to do this with either Lumen or Dingo?


Solution

  • Yes, you can. But it's a little bit more complicated than in your example, but it's still a one-liner. Just define a closure and invoke your controller within it instead of passing the FQCN controller name directly.

    routes/web.php

    $app->get("api/v{version}/users", function ($version) use ($app) {
        return $app->make("App\Api\V{$version}\Controllers\UserController")->show();
    });
    

    If someone else is interested (as I was) how to achieve the same in an laravel installation: Just use the method Controller::callAction() after the controller was resolved

    Route::get("api/v{version}/test", function ($version) {
        return app()->make('App\Api\V{$version}\Controllers\UserController')->callAction("show", [/* arguments */]);
    });