【问题标题】:Using Route Prefixes in Lumen在 Lumen 中使用路由前缀
【发布时间】:2016-06-08 05:45:34
【问题描述】:

来自 Lumen 5.2 文档:

前缀组属性可用于为每个路由添加前缀 具有给定 URI 的组。例如,您可能希望为所有路由添加前缀 组内具有 admin 的 URI:

$app->group(['prefix' => 'admin'], function () use ($app) {
    $app->get('users', function ()    {
        // Matches The "/admin/users" URL
    });
});

我的代码:

$app->group(['prefix' => 'v1'], function () use ($app) {
    $app->get('lessons', function ()    {
        ['as' => 'lessons.index', 'uses' => 'LessonsController@index'];
    });
});

这会返回 200,但它显然没有在 LessonsController 上调用 index() 方法。

我也试过这个:

$app->group(['prefix' => 'v1'], function () use ($app) {
    $app->get('lessons', ['as' => 'lessons.index', 'uses' => 'LessonsController@index']);
});

ReflectionException in Container.php line 738: Class LessonsController does not exist 中的结果

【问题讨论】:

    标签: php lumen lumen-5.2 lumen-routing


    【解决方案1】:

    我目前正在使用这样的前缀:

    $app->group(['namespace' => "App\Http\Controllers", 'prefix' => 'v1'], function($app){
        $app->get('/lessons', 'LessonsController@index');   
    });
    

    这在我的 Lumen 版本中运行良好。您将访问 URL /v1/lessons,它由 LessonsController 中的 index() 方法处理

    注意:Lumen 文档似乎遗漏了为了做到这一点,您需要 'namespace' => "App\Http\Controllers" 键值对才能使其工作。

    【讨论】:

    • 我刚刚粘贴了您所写的内容,但仍然收到错误 ReflectionException in Container.php line 738: Class LessonsController does not exist -- Lumen 的哪个版本适合您?
    • 如果我只是做$app->get('/v1/lessons', 'LessonsController@index'); 而不用前缀包裹它,那么它可以工作,所以控制器显然存在并且正确。
    • 您可以尝试运行composer dump-autoload。但是,我确实错过了我的名称空间位于不同的命名空间中,因此我的数组中也有 'namespace' => "App\Http\Controllers\Backend",也许可以尝试 Lumen 首次出现时需要的 App\Http\Controllers,但他们现在应该已经解决了这个问题。
    • 我只是做了一点测试,你确实是对的。该文档似乎不正确,并且您确实需要数组中的namespace。我已经更新了我的答案以包含它
    • 谢谢,太好了!
    猜你喜欢
    • 1970-01-01
    • 2019-07-06
    • 1970-01-01
    • 2014-01-03
    • 1970-01-01
    • 2016-03-26
    • 2018-09-08
    • 2015-12-10
    • 2011-06-09
    相关资源
    最近更新 更多