我尽量不使用常量,我更喜欢类常量而不是全局常量。但是,当常量不可避免时,无论出于何种原因,我都会使用 .ini 配置文件和 Bootstrap/library/model 类常量。
.ini 配置常量示例
(假设default zf project structure)
application/configs/application.ini
constants.MESSAGE_1 = "Message 1"
constants.MESSAGE_2 = "Message 2"
Bootstap.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/configs/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;
}
}