如何在 Zend Framework 2 中访问路由、发布、获取等参数
如何在zf2中获取与页面请求相关的各种参数?像 post/get 参数、被访问的路由、发送的标题和上传的文件.
How can I get various parameters related to the page request in zf2? Like post/get parameters, the route being accessed, headers sent and files uploaded.
推荐答案
最简单的方法是使用 Params 插件,在 beta5 中引入.它具有实用方法,可以轻松访问不同类型的参数.与往常一样,阅读测试可以证明对于了解应该如何使用某物很有价值.
The easiest way to do that would be to use the Params plugin, introduced in beta5. It has utility methods to make it easy to access different types of parameters. As always, reading the tests can prove valuable to understand how something is supposed to be used.
要获取控制器中命名参数的值,您需要为要查找的参数类型选择适当的方法并传入名称.
To get the value of a named parameter in a controller, you will need to select the appropriate method for the type of parameter you are looking for and pass in the name.
$this->params()->fromPost('paramname'); // From POST
$this->params()->fromQuery('paramname'); // From GET
$this->params()->fromRoute('paramname'); // From RouteMatch
$this->params()->fromHeader('paramname'); // From header
$this->params()->fromFiles('paramname'); // From file being uploaded
所有这些方法还支持默认值,如果没有找到给定名称的参数,将返回这些默认值.
All of these methods also support default values that will be returned if no parameter with the given name is found.
$orderBy = $this->params()->fromQuery('orderby', 'name');
访问 http://example.com/?orderby=birthdate 时,$orderBy 的值为 birthdate.
访问 http://example.com/ 时,$orderBy 将具有 默认 值 name.
When visiting http://example.com/?orderby=birthdate,
$orderBy will have the value birthdate.
When visiting http://example.com/,
$orderBy will have the default value name.
要获取一种类型的所有参数,只需不要传入任何内容,Params 插件将返回一个以名称为键的值数组.
To get all parameters of one type, just don't pass in anything and the Params plugin will return an array of values with their names as keys.
$allGetValues = $this->params()->fromQuery(); // empty method call
访问http://example.com/?orderby=birthdate&filter=hasphone时 $allGetValues 将是一个类似
array(
'orderby' => 'birthdate',
'filter' => 'hasphone',
);
如果您查看源代码 对于 Params 插件,您将看到它只是其他控制器的薄包装器,以允许更一致的参数检索.如果您出于某种原因想要/需要直接访问它们,您可以在源代码中看到它是如何完成的.
If you check the source code for the Params plugin, you will see that it's just a thin wrapper around other controllers to allow for more consistent parameter retrieval. If you for some reason want/need to access them directly, you can see in the source code how it's done.
$this->getRequest()->getRequest('name', 'default');
$this->getEvent()->getRouteMatch()->getParam('name', 'default');
注意:您可以使用超全局变量 $_GET、$_POST 等,但不鼓励这样做.
NOTE: You could have used the superglobals $_GET, $_POST etc., but that is discouraged.
相关文章