【问题标题】:Slim Route Group not passing url variable to the callbackSlim Route Group 未将 url 变量传递给回调
【发布时间】:2015-07-09 22:56:21
【问题描述】:

我正在尝试使用 slim 的路由组,但我无法获取 url 参数以传递任何内容。

$app->group('/contest/:id', function($id) use ($API){
    error_log('THIS IS THE CONTEST ID: '.$id); // id is blank... why?
    $API->authorize('contest', $id);
    $contest = new Contest($id);

    $app->get('', function() use ($contest, $API){
        $data = $contest->getSettings();
        $API->output($data);
    });

    $app->get('/settings', function() use ($contest, $API){
        $data = $contest->getSettings();
        $API->output($data);
    });

    $app->get('/stats', function() use ($contest, $API){
        $data = $contest->getStats();
        $API->output($data);
    });

    $app->get('/fields', function() use ($contest, $API){
        $data = $contest->getFields();
        $API->output($data);
    });
});

为什么我不能在回调函数中访问$id?这不是路线组的重点吗?

【问题讨论】:

    标签: php slim


    【解决方案1】:

    我试图重现这一点 - 使用最后一个稳定版本 2.6.2 - 并且(可能)遇到了和你一样的问题。

    警告:{closure}() 缺少参数 1

    组中的路由参数可以放在子级的回调中:

    $app->group('/contest/:id', function() use ($API){
    
        $app->get('', function($id) use ($contest, $API){
            $API->authorize('contest', $id);
            $contest = new Contest($id);
            $data = $contest->getSettings();
            $API->output($data);
        });
    });
    

    但是,是的,在每条路线上都进行授权是很丑陋的,也许你可以在某种 middleware 中做到这一点?我认为文档页面上的最后一个看起来很符合您的需求。

    编辑

    哦,我最近找到了this issue,@Gisheri 已经得到了 Slim 维护者的回答。

    【讨论】:

    • 是的,谢谢,这就是我最终所做的......也许有一天它会成为一个功能。
    • 嗯,我不知道即将到来的 Slim3 中的实现。
    猜你喜欢
    • 2011-11-13
    • 1970-01-01
    • 2018-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多