php – Laravel动态控制器路由

我使用Laravel 5.4,现在我想制作动态路由到控制器,这意味着我可以直接访问UserController和Profile函数抛出路径,例如.

GET http://localhost/user/profile?userid=123

上面的示例URL将在?之后使用动态参数访问UserController和功能配置文件.如果我想访问不同的控制器,我只需要将用户参数更改为控制器名称.

我创建了这样的路线,它的工作原理.

Route::get('v1/{controller_name}/{function_name}/{query?}', function ($controller_name, $function_name){

    $app = app();
    $controller = $app->make('\App\Http\Controllers\Api\\'.$controller_name.'Controller');
    return $controller->callAction($function_name, $parameters = array());
});

但我不知道如何传递参数.

还有其他更好的方法吗?

最佳答案 如果我理解正确的话,我不确定,但您可能需要查看以下内容.

Route::get('v1/{controller_name}/{function_name}/{query?}',
        function ($controller_name, $function_name, $query = null) {
    var_dump($controller_name, $function_name, $query);
});

访问http://localhost/v1/my-controller/my-function/my-parameter网址输出:

string 'my-controller' (length=13)
string 'my-function' (length=11)
string 'my-parameter' (length=12)

访问http://localhost/v1/my-controller/my-function URL输出:

string 'my-controller' (length=13)
string 'my-function' (length=11)
null

为了进一步扩展这个想法,可以写:

Route::get('v1/{controller_name}/{function_name}/{query?}/{query2?}',
        function ($controller_name, $function_name, $query = null, $query2 = null) {
    var_dump($controller_name, $function_name, $query, $query2);
});

http://localhost/v1/my-controller/my-function/my-parameter/my-parameter2

string 'my-controller' (length=13)
string 'my-function' (length=11)
string 'my-parameter' (length=12)
string 'my-parameter2' (length=13)

http://localhost/v1/my-controller/my-function

string 'my-controller' (length=13)
string 'my-function' (length=11)
null
null

然后你可以使用:

// ...
return $controller->callAction($function_name, $parameters = [
    'param1' => $query,
    'param2' => $query2,
]);
// ...
点赞