如何从Zend Framework 2中的视图文件访问路由,发布,获取,服务器等参数

时间:2013-04-15 07:37:14

标签: zend-framework2 zend-route zend-view

我们如何以ZF2方式从 VIEW 文件访问路由,发布,获取,服务器参数?

Here我发现了几乎相同的问题,但没有提到关于视图的问题,也没有在任何地方回答

由于

2 个答案:

答案 0 :(得分:11)

您必须创建一个视图助手来为您获取这些参数。

查看助手

只需将Zend\Mvc\Controller\Plugin\Params复制到App\View\Helper\Params并进行一些调整:

<?php

namespace App\View\Helper;

use Zend\Mvc\MvcEvent;
use Zend\Stdlib\RequestInterface;
use Zend\View\Helper\AbstractHelper;

class Params extends AbstractHelper
{
    protected $request;

    protected $event;

    public function __construct(RequestInterface $request, MvcEvent $event)
    {
        $this->request = $request;
        $this->event = $event;
    }

    public function fromPost($param = null, $default = null)
    {
        if ($param === null)
        {
            return $this->request->getPost($param, $default)->toArray();
        }

        return $this->request->getPost($param, $default);
    }

    public function fromRoute($param = null, $default = null)
    {
        if ($param === null)
        {
            return $this->event->getRouteMatch()->getParams();
        }

        return $this->event->getRouteMatch()->getParam($param, $default);
    }
}

只需使用$controller$request属性替换$event的所有实例。你明白了。 (不要忘记复制DocBlock评论!)

接下来,我们需要一个工厂来创建视图助手的实例。在App\Module课程中使用以下内容:

<?php
namespace App;

use App\View\Helper;
use Zend\ServiceManager\ServiceLocatorInterface;

class Module
{
    public function getViewHelperConfig()
    {
        return array(
            'factories' => array(
                'Params' => function (ServiceLocatorInterface $helpers)
                {
                    $services = $helpers->getServiceLocator();
                    $app = $services->get('Application');
                    return new Helper\Params($app->getRequest(), $app->getMvcEvent());
                }
            ),
        );
    }
}

如何使用

一旦你掌握了这一切,你就会在家中。只需在视图中调出params视图助手:

// views/app/index/index.phtml
<?= $this->params('controller') ?>
<?= $this->params()->fromQuery('wut') ?>

希望这能回答你的问题!如果您需要任何澄清,请告诉我。

答案 1 :(得分:1)

我为此目的创建了 Params View Helper (正如@radnan建议的那样)。

通过composer

安装
  

作曲家需要tasmaniski / zf2-params-helper

注册新模块

'modules' => array(
    '...',
    'ParamsHelper'
),

并使用它

$this->params()->fromPost();  //read all variables from $_POST
$this->params()->fromRoute(); //read all variables from Routes
$this->params()->fromQuery(); //read all variables from $_GET

查看完整文档GitHub source