Zend,Application.ini中的全局变量?

can*_*nim 8 zend-framework global-variables

我有一个问题,因为我需要一个全局静态变量,我有问题是有可能将它添加到application.ini文件,该怎么做?

或者我必须:

  1. 用静态变量创建抽象类,
  2. 在Zend_Registry中注册它以从所有应用程序访问此变量(在Bootstrap文件中注册)
  3. 我可以使用它,或者更容易,我的意思是"自动方式"来做它?

谢谢你的建议!Regars,

TuK*_*TuK 12

在Application.ini文件中

someservice.apikey  = 12345678
someservice.passkey = 87654321
Run Code Online (Sandbox Code Playgroud)

在引导程序中

public function _initSomeservice()
{
    $someservice = $this->getOption('someservice');
    Zend_Registry::set('someservice', $someservice);
}
Run Code Online (Sandbox Code Playgroud)

从Registry注册

$config = Zend_Registry::get('someservice');
Run Code Online (Sandbox Code Playgroud)


can*_*nim 6

对我来说最好的解决方案是在index.php文件中创建一个变量.我添加了:defined('VARIABLE_NAME')|| define('VARIABLE_NAME','Something here');

现在我可以从任何地方访问它; D非常感谢!


Jur*_*man 5

我不会使用Zend_Registry和常量,原因有两个

  1. 在注册表中,您永远不会确定变量发生了什么.应用程序的每个部分都可以更改它们,您不会被注意到.我认为注册表实际上是一个anit-pattern.
  2. 常量不必要地污染您的应用程序.如果你为每个配置使用一些常量怎么办?你必须保留一个包含所有常量的附加文档,维护起来很糟糕.

最好的选择是直接从引导程序获取配置对象.在下面的示例中,我假设您在application.ini中有这个:

someservice.apikey  = 12345678
someservice.passkey = 87654321
Run Code Online (Sandbox Code Playgroud)

引导程序在frontController中设置为参数.如果你有一个动作控制器,这就像这样简单:

$serviceOptions = $this->getInvokeArg('bootstrap')->getOption('someservice');
Run Code Online (Sandbox Code Playgroud)

如果您在控制器中实例化了服务,则现在可以通过构造函数和/或setter传递它们.

如果你想获得不在你的控制器内,而是在其他地方的选项,你可以使用frontController实现的单例模式.所以在任何地方(当然只在调度期间,而不是在自举期间)你能够做到这一点:

$frontController = Zend_Controller_Front::getInstance();
$serviceOptions  = $frontController->getParam('bootstrap')
                                   ->getOption('someservice');
Run Code Online (Sandbox Code Playgroud)

使用上面的方法你很安全,你总是有正确的配置选项,而不是一些可能变异的配置选项.


use*_*791 1

您可以在 application.ini 和 Bootsrap.php 中指定值,您可以读取该值并将其保存在 Zend_Registry 中。您还可以使用 PHP 定义方法来创建常量(如果您的 veriable 是常量)。