php 如何在 ZF2/ZF3 url 视图助手中添加查询参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12785190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can you add query parameters in the ZF2 / ZF3 url view helper
提问by Ross
I'm attempting to create a url with a query string using a route, like so:
我正在尝试使用路由创建一个带有查询字符串的 url,如下所示:
$this->url('users') -> /users
$this->url('users', ['sort' => 'desc']) -> /users?sort=desc
However this doesn't seem to work (the second helper actually outputs /users). According to this unofficial, out-of-date documentationthere was once a way to do this by appending /queryto the route name, however this gives a route-not-found exception.
然而,这似乎不起作用(第二个助手实际上输出/users)。根据这个非官方的、过时的文档,曾经有一种方法可以通过附加/query到路线名称来做到这一点,但是这会导致未找到路线的异常。
Can this be done using the current url helper?
这可以使用当前的 url helper 来完成吗?
采纳答案by Andreas Linden
You can create a child route for your users route like this:
您可以为您的用户路由创建子路由,如下所示:
'users' => array(
'type' => 'Literal',
'options' => array(
'route' => '/users',
'defaults' => array(
'__NAMESPACE__' => 'User\Controller',
'controller' => 'Index',
'action' => 'list',
),
),
'may_terminate' => true,
'child_routes' => array(
'query' => array(
'type' => 'Query',
),
),
),
then you can assemble $this->url('users/query', array('sort' => 'desc')).
然后你就可以组装了$this->url('users/query', array('sort' => 'desc'))。
Don't forget to set may_terminateto true!
不要忘记设置may_terminate为true!
回答by dVaffection
Since version 2.1.4 you come across user error
从 2.1.4 版开始,您会遇到用户错误
Query route deprecated as of ZF 2.1.4; use the "query" option of the HTTP router\'s assembling method instead
自 ZF 2.1.4 起不推荐使用查询路由;改用 HTTP 路由器组装方法的“查询”选项
Usage example:
用法示例:
$name = 'index/article';
$params = ['article_id' => $articleId];
$options = [
'query' => ['param' => 'value'],
];
$this->url($name, $params, $options);
回答by Matthew Fedak
This can be done using the current URL view helper yes.
这可以使用当前的 URL 视图助手来完成。
$this->url('users', [], array('query' => array('sort' => 'desc')))
You do not need to have query string child routes setup. As long as you have a route setup for 'users', you can just look for the 'sort' param in your controller and use where required.
您不需要设置查询字符串子路由。只要您为“用户”设置了路由,您就可以在控制器中查找“排序”参数并在需要时使用。

