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

时间:2022-10-09 23:17:31

I have a Zend Framework application based on the quick-start setup.

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

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:

我已经让演示工作了,现在我正在实例化一个新的模型类来做一些真正的工作。在我的控制器中,我想将配置参数(在application.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();
    }
}

The example above does allow access to the options, but seems extremely round-about. Is there a better way to access the configuration?

上面的示例允许访问选项,但似乎非常圆。有更好的方法来访问配置吗?

7 个解决方案

#1


47  

I always add the following init-method to my bootstrap to pass the configuration into the registry.

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

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

#2


22  

Since version 1.8 you can use the below code in your Controller:

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

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

#3


6  

Alternatively, instead of using Zend_Registry you could also create a singleton Application class that will contain all application info, with public member functions that allow you to access the relevant data. Below you can find a snippet with relevant code (it won't run as is, just to give you an idea how it can be implemented) :

或者,您也可以创建一个包含所有应用程序信息的单例Application类,而不是使用Zend_Registry,其中包含允许您访问相关数据的公共成员函数。您可以在下面找到包含相关代码的代码段(它不会按原样运行,只是为了让您了解如何实现它):

final class Application
{
    /**
     * @var Zend_Config
     */    
    private $config = null;

    /**
     * @var Application
     */    
    private static $application;

    // snip

    /**
     * @return Zend_Config
     */
    public function getConfig()
    {
        if (!$this->config instanceof Zend_Config) {
            $this->initConfig();
        }
        return $this->config;
    }

    /**
     * @return Application
     */
    public static function getInstance()
    {
        if (self::$application === null) {
            self::$application = new Application();
        }
        return self::$application;
    }

    /**
     * Load Configuration
     */
    private function initConfig()
    {
        $configFile = $this->appDir . '/config/application.xml';
        if (!is_readable($configFile)) {
            throw new Application_Exception('Config file "' . $configFile . '" is not readable');
        }
        $config = new Zend_Config_Xml($configFile, 'test');
        $this->config = $config;
    }

    // snip

    /**
     * @param string $appDir
     */
    public function init($appDir)
    {
        $this->appDir = $appDir;
        $this->initConfig();
        // snip
    }

    public function run ($appDir)
    {
        $this->init($appDir);
        $front = $this->initController();
        $front->dispatch();            
    }
}

Your bootstrap would look like this :

你的bootstrap看起来像这样:

require 'Application.php';
try {
    Application::getInstance()->run(dirname(dirname(__FILE__)));
} catch (Exception $e) {
    header("HTTP/1.x 500 Internal Server Error");
    trigger_error('Application Error : '.$e->getMessage(), E_USER_ERROR);
}

When you want to access the configuration you would use the following :

如果要访问配置,可以使用以下命令:

$var = Application::getInstance()->getConfig()->somevar;

#4


3  

In most ZF apps, the application object is declared in the global scope (see public/index.php in apps created with ZFW_DISTRIBUTION/bin/zf.sh).

在大多数ZF应用程序中,应用程序对象在全局范围内声明(请参阅使用ZFW_DISTRIBUTION / bin / zf.sh创建的应用程序中的public / index.php)。

It's not exactly the ZF way, but you can access the object with $GLOBALS['application']. It kinda feels like cheating, but if you're after performance, this will likely be the quickest option.

它不完全是ZF方式,但您可以使用$ GLOBALS ['application']访问该对象。这有点像作弊,但如果你在表演后,这可能是最快的选择。

$manager = new My_Model_Manager($GLOBALS['application']->getOption('my'));

#5


1  

$this->getInvokeArg('bootstrap')->getOptions();
// or 

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

#6


0  

I've define a short hand in some place I require_once() in the beginning of boostrap:

我在boostrap的开头我在require_once()的某个地方定义了一个简短的手:

function reg($name, $value=null) {
    (null===$value) || Zend_Registry::set($name, $value);
    return Zend_Registry::get($name);
}

and in the bootstrap I have a:

在引导程序中我有一个:

protected function _initFinal()
{
    reg('::app', $this->getApplication());
}

then I can get the Application instance anywhere by use:

然后我可以通过使用获取Application实例:

$app = reg('::app');

#7


0  

A really simple way to access the configuration options is by directly accessing the globally defined $application variable.

访问配置选项的一种非常简单的方法是直接访问全局定义的$ application变量。

class My_UserController extends Zend_Controller_Action {
    public function indexAction() {
        global $application;
        $options = $application->getOptions();
    }
}

#1


47  

I always add the following init-method to my bootstrap to pass the configuration into the registry.

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

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

#2


22  

Since version 1.8 you can use the below code in your Controller:

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

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

#3


6  

Alternatively, instead of using Zend_Registry you could also create a singleton Application class that will contain all application info, with public member functions that allow you to access the relevant data. Below you can find a snippet with relevant code (it won't run as is, just to give you an idea how it can be implemented) :

或者,您也可以创建一个包含所有应用程序信息的单例Application类,而不是使用Zend_Registry,其中包含允许您访问相关数据的公共成员函数。您可以在下面找到包含相关代码的代码段(它不会按原样运行,只是为了让您了解如何实现它):

final class Application
{
    /**
     * @var Zend_Config
     */    
    private $config = null;

    /**
     * @var Application
     */    
    private static $application;

    // snip

    /**
     * @return Zend_Config
     */
    public function getConfig()
    {
        if (!$this->config instanceof Zend_Config) {
            $this->initConfig();
        }
        return $this->config;
    }

    /**
     * @return Application
     */
    public static function getInstance()
    {
        if (self::$application === null) {
            self::$application = new Application();
        }
        return self::$application;
    }

    /**
     * Load Configuration
     */
    private function initConfig()
    {
        $configFile = $this->appDir . '/config/application.xml';
        if (!is_readable($configFile)) {
            throw new Application_Exception('Config file "' . $configFile . '" is not readable');
        }
        $config = new Zend_Config_Xml($configFile, 'test');
        $this->config = $config;
    }

    // snip

    /**
     * @param string $appDir
     */
    public function init($appDir)
    {
        $this->appDir = $appDir;
        $this->initConfig();
        // snip
    }

    public function run ($appDir)
    {
        $this->init($appDir);
        $front = $this->initController();
        $front->dispatch();            
    }
}

Your bootstrap would look like this :

你的bootstrap看起来像这样:

require 'Application.php';
try {
    Application::getInstance()->run(dirname(dirname(__FILE__)));
} catch (Exception $e) {
    header("HTTP/1.x 500 Internal Server Error");
    trigger_error('Application Error : '.$e->getMessage(), E_USER_ERROR);
}

When you want to access the configuration you would use the following :

如果要访问配置,可以使用以下命令:

$var = Application::getInstance()->getConfig()->somevar;

#4


3  

In most ZF apps, the application object is declared in the global scope (see public/index.php in apps created with ZFW_DISTRIBUTION/bin/zf.sh).

在大多数ZF应用程序中,应用程序对象在全局范围内声明(请参阅使用ZFW_DISTRIBUTION / bin / zf.sh创建的应用程序中的public / index.php)。

It's not exactly the ZF way, but you can access the object with $GLOBALS['application']. It kinda feels like cheating, but if you're after performance, this will likely be the quickest option.

它不完全是ZF方式,但您可以使用$ GLOBALS ['application']访问该对象。这有点像作弊,但如果你在表演后,这可能是最快的选择。

$manager = new My_Model_Manager($GLOBALS['application']->getOption('my'));

#5


1  

$this->getInvokeArg('bootstrap')->getOptions();
// or 

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

#6


0  

I've define a short hand in some place I require_once() in the beginning of boostrap:

我在boostrap的开头我在require_once()的某个地方定义了一个简短的手:

function reg($name, $value=null) {
    (null===$value) || Zend_Registry::set($name, $value);
    return Zend_Registry::get($name);
}

and in the bootstrap I have a:

在引导程序中我有一个:

protected function _initFinal()
{
    reg('::app', $this->getApplication());
}

then I can get the Application instance anywhere by use:

然后我可以通过使用获取Application实例:

$app = reg('::app');

#7


0  

A really simple way to access the configuration options is by directly accessing the globally defined $application variable.

访问配置选项的一种非常简单的方法是直接访问全局定义的$ application变量。

class My_UserController extends Zend_Controller_Action {
    public function indexAction() {
        global $application;
        $options = $application->getOptions();
    }
}