如何从Zend Framework 2(zf2)中的View访问应用程序配置?

Oma*_* S. 6 zend-view zend-framework2

我想从视图中访问应用程序配置.如何在ZF 2中实现这一目标?

edi*_*igu 9

实际上,您不需要在视图中访问应用程序配置.在MVC中,视图只负责显示/呈现数据(输出),不应包含任何业务或应用程序逻辑.

如果你真的想这样做,你可以简单地传递到你的控制器中查看如下:

<?php
namespace YourModule\Controller;

use Zend\View\Model\ViewModel;

// ...

public function anyAction()
{
    $config = $this->getServiceLocator()->get('config');
    $viewModel = new ViewModel();
    $viewModel->setVariables(array('config' => $config ));
    return $viewModel;
}

// ...
?>
Run Code Online (Sandbox Code Playgroud)

所以在你的view.phtml文件中;

<div class="foo">
 ...
 <?php echo $this->config; ?>
 ...
</div>
Run Code Online (Sandbox Code Playgroud)

  • 虽然您的控制器中不应该有业务逻辑,但配置仍可能影响渲染/显示逻辑,例如配置值告诉视图它应该呈现什么主题.我仍然同意它应该是控制器通过ViewModel将配置值发送到视图 - 尽可能细粒度,而不是将全局配置从ServiceManager中拉出来的视图. (2认同)

Mik*_*lov 8

您应该创建一个视图助手.

config.php文件

<?php
namespace Application\View\Helper;

class Config extends \Zend\View\Helper\AbstractHelper
{
    public function __construct($config)
    {
        $this->key = $config;
    }

    public function __invoke()
    {
        return $this->config;
    }

}
Run Code Online (Sandbox Code Playgroud)

Module.php或theme.config.php

return array(
    'helpers' => array(
    'factories' => array(
        'config' => function ($sm) {
            return new \Application\View\Helper\Config(
                    $sm->getServiceLocator()->get('Application\Config')->get('config')
            );
        },
    )
),
);
Run Code Online (Sandbox Code Playgroud)

然后,您可以在任何视图中使用配置变量.

echo $this->config()->Section->key;
Run Code Online (Sandbox Code Playgroud)


Elv*_*tti 7

使用ZF 2.2.1(不确定以前的版本是否可行),您只需添加助手即可注入任何东西

# module.config.php
...
'view_helpers' => array(
  'invokables' => array(
     'yourHelper' => 'Application\View\Helper\YourHelper',
  ),
Run Code Online (Sandbox Code Playgroud)

),...

并编写YourHelper实现接口Zend\ServiceManager\ServiceLocatorAwareInterface.您必须实现接口的两种方法(简单的setter和getter).您现在可以访问服务定位器,并获取配置:

namespace Application\View\Helper;

class YourHelper implements Zend\ServiceManager\ServiceLocatorAwareInterface
{

  public function __invoke()
  {
    $config = $this->getServiceLocator()->getServiceLocator()->get('Config');

    // $config is the object you need

    return $config;
  }

  public function getServiceLocator()
  {
     return $this->serviceLocator;  
  }

  public function setServiceLocator(\Zend\ServiceManager\ServiceLocatorInterface $serviceLocator)
  {
    $this->serviceLocator = $serviceLocator;  
    return $this;  
  }
}
Run Code Online (Sandbox Code Playgroud)

更多信息,请访问http://robertbasic.com/blog/working-with-custom-view-helpers-in-zend-framework-2

帮助访问配置https://gist.github.com/elvisciotti/6592837