如何从控制器访问 Zend 框架应用程序的配置?

2022-08-30 17:25:08

我有一个基于快速启动设置的Zend框架应用程序。

我已经让演示工作,现在正要实例化一个新的模型类来做一些真正的工作。在我的控制器中,我想将配置参数(在应用程序中指定.ini)传递给我的模型构造函数,如下所示:

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();
    }
}

上面的示例确实允许访问这些选项,但似乎非常迂回。有没有更好的方法来访问配置?


答案 1

我总是将以下初始化方法添加到我的引导程序中,以将配置传递到注册表中。

protected function _initConfig()
{
    $config = new Zend_Config($this->getOptions(), true);
    Zend_Registry::set('config', $config);
    return $config;
}

这将缩短您的代码:

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();
    }
}

答案 2

从版本 1.8 开始,您可以在控制器中使用以下代码:

$my = $this->getInvokeArg('bootstrap')->getOption('my');

推荐