我想/必须管理 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/