如何在 cakephp 3 中从 url 访问参数

how to access parameters from url in cakephp 3

在cakephp 3的cook book中给出了使用

构建url
echo $this->Url->build([
    "controller" => "Posts",
    "action" => "view",
    "foo" => "bar"
]);

这将输出为

/posts/view/foo:bar

如何在操作中访问 foo:bar 并保存在变量 $foo 中?

食谱有误,所以我打开了this

如果您使用此代码

echo $this->Url->build([
    "controller" => "Posts",
    "action" => "view",
    "foo" => "bar"
]);

你会得到这样的url

/posts/view/?foo=bar

手册here解释了如何访问 GET 参数

你可以做到

$this->request->query('foo');

 $this->request->query['foo'];

第一个是空安全的,这意味着如果未设置“foo”参数,您只会得到 null 而不是错误

编辑

3.4.0 之后的新语法是

$this->request->getQuery('foo');

或者在一行中将所有参数作为数组获取:

$params = $this->request->getQueryParams();

CakePHP 3.*版本可以使用request查询:

$this->request->getQuery('utm_source')