0

创建包含所有应用程序常量变量的类的最佳位置在哪里?
是吗:-引导
程序 -在应用程序公共库中

例如:1-当我从数据库中检索图像名称时,如果此记录没有图像,我想在某处放置一个默认值,以便我可以在我的模型中使用它

** 我在所有应用程序中使用的常量,所以如果我更改它,我不想回到我的代码中的所有内容并在任何地方更改它

4

2 回答 2

5

application.ini 是最好的地方,例如在那里定义一些常量

constants.PUBLIC_PATH =  APPLICATION_PATH "/../public/"
constants.THEME = blue

然后在你的引导做

protected function setConstants($constants)
{
    foreach($constants as $name => $value)
    {
         if(!defined($name))
            define($name, $value);
    }

}

ZF 从配置中获取“常量”并在引导程序中调用 setConstants 方法,传递所有以常量为前缀的行,因此它是一个数组。

于 2012-05-02T06:51:07.970 回答
1

我尝试不使用常量,并且更喜欢类常量而不是全局常量。但是,当常量不可避免时,无论出于何种原因,我都会使用 .ini 配置文件和 Bootstrap/library/model 类常量。

.ini 配置常量的示例

(假设默认 zf 项目结构

应用程序/配置/application.ini

constants.MESSAGE_1 = "Message 1"
constants.MESSAGE_2 = "Message 2"

引导程序.php

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
    protected function _initConstants()
    {
        $options = $this->getOption('constants');

        if (is_array($options)) {
            foreach($options as $key => $value) {
                if(!defined($key)) {
                    define($key, $value);
                }
            }
        }
    }

    // ...
}

控制器中的示例用法:

class IndexController extends Zend_Controller_Action
{
    public function indexAction()
    {
        $this->view->message1 = MESSAGE_1;
        $this->view->message2 = MESSAGE_2;
    }
}

我将扩展上述内容以允许配置常量的定义方式例如,您可能希望所有常量都大写或不大写,并允许或禁止已定义的常量,因此:

应用程序/配置/application.ini

constants.forceUppercase = 1
constants.allowAlreadyDefined = 1
constants.set.message_1 = "Message 1"
constants.set.message_2 = "Message 2"

引导程序:

    protected function _initConstants()
    {
        $options = $this->getOption('constants');

        if (isset($options['set']) && is_array($options['set'])) {

            if (isset($options['forceUppercase'])
                && (bool) $options['forceUppercase']) {
                $options['set'] = array_change_key_case($options['set'], CASE_UPPER);
            }

            $allowAlreadyDefined = false;
            if (isset($options['allowAlreadyDefined'])
                && (bool) $options['allowAlreadyDefined']) {
                $allowAlreadyDefined = true;
            }

            foreach($options['set'] as $key => $value) {
                if (!defined($key)) {
                    define($key, $value);
                } elseif (!$allowAlreadyDefined) {
                    throw new InvalidArgumentException(sprintf(
                        "'%s' already defined!", $key));
                }
            }
        }
    }

引导类常量

可能是您自己的库,或模型类等,这取决于。

在引导程序中:

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
    const MESSAGE_CONSTANT = "Hello World";

    // ...
}

控制器中的示例用法:

class IndexController extends Zend_Controller_Action
{
    public function indexAction()
    {
        $this->view->message = Bootstrap::MESSAGE_CONSTANT;
    }
}
于 2012-05-02T09:05:27.217 回答