获取Slim上的请求参数


Getting request parameters on Slim

我试图动态获取请求参数名称和值,但数组始终为空。这是get路由:

$app->get('/get/profile/:id_user', function ($id_user) use ($app) {
    print_r($app->request()->params());
});

我是这样从浏览器调用它的:

http://localhost/get/profile/9492

这应该返回一个包含id_user => 9492的数组,但它是空的。

知道为什么吗?

注意:请在尝试此代码之前阅读更新说明。更新说明是我在这个回答中的第一个评论。

无法测试,但请尝试以下操作:

$app->get('/get/profile/:id_user', function ($id_user) use ($app) {
    $req = $app->request();
    print_r($req->params());
});

参考文档:http://docs.slimframework.com/#Request-Method

更新:好了,经过一番挖掘,params()方法需要一个参数。如果调用时不带参数,则会引发Notice。检查源代码发现,这个不带参数的函数调用返回null。见Http/Request.php第199行。此外,由于某种原因,柯里化似乎无法检索参数,因此您必须使用具有预期值的函数参数$id_user

您可以使用以下命令:

$app->get("/test.:format/:name",function() use ($app){
  $router = $app->router();
  print_r($router->getCurrentRoute()->getParams());
});

也是一个配置问题。

try_files $uri $uri/ /index.php?$query_string;