如何从控制器访问 Zend Framework 应用程序的配置? [英] How can I access the configuration of a Zend Framework application from a controller?
问题描述
我有一个基于快速启动设置的 Zend Framework 应用程序.
I have a Zend Framework application based on the quick-start setup.
我已经让演示工作了,现在正在实例化一个新的模型类来做一些实际的工作.在我的控制器中,我想将一个配置参数(在 application.ini 中指定)传递给我的模型构造函数,如下所示:
I've gotten the demos working and am now at the point of instantiating a new model class to do some real work. In my controller I want to pass a configuration parameter (specified in the application.ini) to my model constructor, something like this:
class My_UserController extends Zend_Controller_Action
{
public function indexAction()
{
$options = $this->getFrontController()->getParam('bootstrap')->getApplication()->getOptions();
$manager = new My_Model_Manager($options['my']);
$this->view->items = $manager->getItems();
}
}
上面的示例确实允许访问选项,但似乎非常迂回.有没有更好的方法来访问配置?
The example above does allow access to the options, but seems extremely round-about. Is there a better way to access the configuration?
推荐答案
我总是将以下 init-method 添加到我的引导程序中,以将配置传递到注册表中.
I always add the following init-method to my bootstrap to pass the configuration into the registry.
protected function _initConfig()
{
$config = new Zend_Config($this->getOptions(), true);
Zend_Registry::set('config', $config);
return $config;
}
这会稍微缩短您的代码:
This will shorten your code a little bit:
class My_UserController extends Zend_Controller_Action
{
public function indexAction()
{
$manager = new My_Model_Manager(Zend_Registry::get('config')->my);
$this->view->items = $manager->getItems();
}
}
这篇关于如何从控制器访问 Zend Framework 应用程序的配置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!