【发布时间】:2011-10-14 11:25:28
【问题描述】:
我已经阅读了我在 StackOverflow 上找到的关于该主题的几乎所有问题,但找不到直接的答案。
这是我的代码:
应用类
<?php
class Application extends Settings {
public function __construct($env, $cacheDir, $configFile) {
self::$_env = $env;
self::$_cacheDir = $cacheDir;
self::$_config = $this->loadConfig($configFile) // reads configs from xml file into Config object
}
// other methods
}
?>
设置类:
<?php
class Settings {
protected static $_env = null;
protected static $_cacheDir = null;
protected static $_config = null;
public static function getEnv() {
return self::$_env;
}
public static function getCacheDir() {
return self::$_cacheDir;
}
public static function getConfig() {
return self::$_config;
}
}
?>
我可以从代码中的任何位置访问设置,如下所示:
<?php
var_dump(Settings::getEnv());
?>
我想从许多不同的地方访问设置。所有值只能设置一次并且不能被覆盖(因此使用 __set 方法的注册表不起作用,因为我可以在应用程序的任何阶段从任何位置设置任何值)
问题:
像这样存储全局设置是一种好习惯吗?这种方法有什么缺点? 也许有更好的方法来做到这一点?
感谢您的回答
【问题讨论】:
-
你是一个类的有效全局状态,引入了一个不完全是单例,但有点像它。它有它的用途,也有它的优点和缺点。我,我更喜欢依赖注入,因为这类结构很难编写测试。
-
@Wrikken 我完全同意你的看法。但我看不到没有单例重写我的代码的方法
标签: php settings global-variables