configuration - 如何从 Zend Framework 2 的布局/ View 脚本中自动加载的配置文件访问配置?

标签 configuration zend-framework2 production-environment application-settings

我想/必须管理 ZF1 style 中的一些设置并向 View 提供有关当前环境的信息。

/config/application.config.php

return array(
    ...
    'module_listener_options' => array(
        ...
        'config_glob_paths' => array('config/autoload/{,*.}{global,local}.php')
    )
);

/config/autoload/env.local.php

return array(
    // allowed values: development, staging, live
    'environment' => 'development'
);

在通用 View 脚本中,我可以通过 Controller 执行此操作,因为 Controller 可以访问服务管理器以及我需要的所有配置:

class MyController extends AbstractActionController {

    public function myAction() {
        return new ViewModel(array(
            'currentEnvironment' => $this->getServiceLocator()->get('Config')['environment'],
        ));
    }

}

是否也可以直接在公共(public) View 中获取配置?

如何访问布局 View 脚本 (/module/Application/view/layout/layout.phtml) 中的配置?

最佳答案

(我的实现/解释)Crisp's suggestion :

配置 View 助手

<?php
namespace MyNamespace\View\Helper;

use Zend\View\Helper\AbstractHelper;
use Zend\View\HelperPluginManager as ServiceManager;

class Config extends AbstractHelper {

    protected $serviceManager;

    public function __construct(ServiceManager $serviceManager) {
        $this->serviceManager = $serviceManager;
    }

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

}

应用程序模块

public function getViewHelperConfig() {
    return array(
        'factories' => array(
            'config' => function($serviceManager) {
                $helper = new \MyNamespace\View\Helper\Config($serviceManager);
                return $helper;
            },
        )
    );
}

布局 View 脚本

// do whatever you want with $this->config()['environment'], e.g.
<?php
if ($this->config()['environment'] == 'live') {
    echo $this->partial('partials/partial-foo.phtml');;
}
?>

关于configuration - 如何从 Zend Framework 2 的布局/ View 脚本中自动加载的配置文件访问配置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16083256/

相关文章:

caching - ZF2 Doctrine2 实体缓存

java - OpenJDK 11或AdoptOpenJDK是否像Oracle JDK一样稳定

java - 如何禁用标记记录器上的可加性?

node.js - 使用 Node JS 设置 Cloud9 SSL 应用程序

scala - 全局禁用 sbt supershell

hibernate - 为 bean 配置 Hibernate 验证

php - 如何在 Twitter Bootstrap 模式窗口中通过 AJAX 加载内容?

forms - 如何在 Zend 框架 2 中禁用 inArray 验证器表单

Laravel 部署到生产环境并在 env 文件问题中混合变量

php - 本地主机+暂存+生产环境?