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 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器