【问题标题】:Prefix all the routes in Lumen为 Lumen 中的所有路由添加前缀
【发布时间】:2016-09-12 15:48:47
【问题描述】:

在 Lumen 中有没有办法为我的所有路由添加前缀?

问题是我通过 URI 对我的 API 进行版本控制,对于我创建的每个组,我必须将前缀设置为 'v1/*',例如:

$app->group(['prefix' => 'v1/students/', 'namespace' => 'App\Http\Controllers\Students\Data'], function () use ($app) {
    $app->get('/', 'StudentController@get');
    $app->get('/{id}', 'StudentController@getByID');
});

【问题讨论】:

    标签: php routes lumen


    【解决方案1】:

    显然,Lumen 中的路由组不继承任何设置,这是为了让路由器更简单、更快 (see comment here)。

    您最好的选择可能是为每个版本创建一个路由组,以便为​​该版本定义一个基本前缀和控制器命名空间。但是,这些路由组中的各个路由需要稍微详细一些。示例如下:

    // creates v1/students, v1/students/{id}
    $app->group(['prefix' => 'v1', 'namespace' => 'App\Http\Controllers'], function () use ($app) {
        $app->get('students', 'Students\Data\StudentController@get');
        $app->get('students/{id}', 'StudentController@getByID');
    });
    
    // creates v2/students, v2/students/{id}, v2/teachers, v2/teachers/{id}
    $app->group(['prefix' => 'v2', 'namespace' => 'App\Http\Controllers'], function () use ($app) {
        $app->get('students', 'Students\Data\StudentController@get');
        $app->get('students/{id}', 'Students\Data\StudentController@getByID');
    
        $app->get('teachers', 'Teachers\Data\TeacherController@get');
        $app->get('teachers/{id}', 'Teachers\Data\TeacherController@getByID');
    });
    

    【讨论】:

    • 嵌套组前缀覆盖父前缀,经过测试。
    • @CarlosFdev 我很抱歉。你是绝对正确的。我已经用另一个建议更新了我的答案。
    【解决方案2】:

    您可以在 /bootstrap/app.php 中为所有路由添加前缀。 目前,应该有类似的东西

    # may be slighlty different, since I typed this from memory
    $app->router->group([
        'namespace' => 'App\Http\Controllers',
    ], function ($router) {
        require __DIR__ . '/../routes/web.php';
    });
    

    如您所见,这会加载 web.php 文件并使 $router 变量可用。 您可以重写它以加载路由目录中的任何 php 文件,并通过

    为所有这些路由添加前缀
    $app->router->group([
        'namespace' => 'App\Http\Controllers',
    ], function ($router) {
        // load all files in routes directory, prefix all of them
        $globalPrefix =  "/v1";
        $router->group(["prefix" => $globalPrefix], function($router) {
            $routes = glob(__DIR__ . '/../routes/*.php');
    
            foreach ($routes as $route) require $route;
        });
    });
    

    如您所见,所有必需的路由都包含在 $router->group 中,并带有您的应用程序范围的路由前缀。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-08
      • 2013-05-29
      • 2018-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多