dpxua26604 2012-08-22 16:05
浏览 55
已采纳

如何在Zend Framework 2中访问路由,发布,获取等参数

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.

  • 写回答

5条回答 默认 最新

  • donvo24600 2012-08-22 16:05
    关注

    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.

    Get a single value

    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.

    Examples:

    $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
    

    Default values

    All of these methods also support default values that will be returned if no parameter with the given name is found.

    Example:

    $orderBy = $this->params()->fromQuery('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.
     

    Get all parameters

    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.

    Example:

    $allGetValues = $this->params()->fromQuery(); // empty method call
    

    When visiting http://example.com/?orderby=birthdate&filter=hasphone $allGetValues will be an array like

    array(
        'orderby' => 'birthdate',
        'filter'  => 'hasphone',
    );
    

    Not using Params plugin

    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.

    Example:

    $this->getRequest()->getRequest('name', 'default');
    $this->getEvent()->getRouteMatch()->getParam('name', 'default');
    

    NOTE: You could have used the superglobals $_GET, $_POST etc., but that is discouraged.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改
  • ¥15 Windows 系统cmd后提示“加载用户设置时遇到错误”
  • ¥50 vue router 动态路由问题
  • ¥15 关于#.net#的问题:End Function
  • ¥15 无法import pycausal
  • ¥15 VS2022创建MVC framework提示:预安装的程序包具有对缺少的注册表值的引用
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义
  • ¥15 嵌入式--定时器使用