【已解决】webman路由

开赛灵

如何做到
只设置一条路由 /api/* 所有生效
例如 /api/user/query

阅读 634
3个回答

葱香小油条
不败少龙

能不能把api/v1,api/v2弄成自动匹配

  • 葱香小油条 2021-08-20

    根据https://github.com/walkor/webman/issues/54作者的答复把v1改成verion,在加点判断版本,类存不存在啥的,自由发挥,如下:
    Route::any('/api/{verion}/{controller}/{action}', function($request, $verion, $controller, $action){
    $class_name = "app\api\{$verion}\controller\" . $controller;
    var_export($verion);
    $controller = new $class_name;
    return call_user_func([$controller, $action], $request);
    });

  • 不败少龙 2021-08-20

    OK 谢谢我去试试

  • yzh52521 2021-08-20

    Route::group('/api',function () {
    Route::group("/{verion}", function () {
    Route::any('/{controller}/{action}', function ($request, $verion, $controller, $action) {
    $class_name = "app\api\{$verion}\controller\" . $controller;
    $controller = new $class_name;
    return call_user_func([$controller, $action], $request);
    });
    });
    });

  • 不败少龙 2021-08-20

    已经写好了 谢谢

不败少龙
Route::group('/api/{verion}', function () {
    Route::group("/{controller}", function () {
        Route::any("/{action}", function (Request $request, $verion, $controller, $action) {
            $class_name = 'app\\api\\controller\\' . $verion . '\\' . $controller;
            if(!is_dir( 'app\\api\\controller\\' . $verion)){
                return json(['code'=>500,'msg'=>$verion.'目录不存在!']);
            }
            if(!class_exists($class_name)){
                return json(['code'=>500,'msg'=>$verion."目录下的控制器: {$controller}不存在!"]);
            }
            if (!method_exists($class_name, $action)) {
                return json(['code'=>500,'msg'=>$verion."目录下的控制器: {$controller}里面的方法: {$action}不存在"]);
            }
            $controller = new $class_name;
            $request->controller = $class_name;
            return call_user_func([$controller, $action], $request);
        });
    });
});

本地目录结构
截图