清除问题:配置容器相对全局define()
ed配置参数的优点是什么?
的优点是所有OOP提供的优势:数据抽象和封装,继承,多态性和更好的设计模式整合。
这个帖子的读者似乎有点困惑,并且专注于你的课而不是主要问题。也clearify这一点,让我给你举个例子:
class Configuration
{
protected $someValue;
}
class ConfigurationDev extends Configuration
{
protected $baseUrl = 'http://devel.yoursite.com/';
}
class ConfigurationLive extends Configuration
{
protected $baseUrl = 'http://www.yoursite.com/';
}
的index.php:
<?php
$config = new ConfigurationDev;
$tracking = new Tracking($config);
...
类跟踪:
class Tracking
{
public function __construct(\Configuration $config) {
if ($config instanceof \ConfigurationLive) {
// We are in live environment, do track
} else {
// Debug Notice: We are NOT in live environment, do NOT track
}
}
}
方案的说明:
想象一下,您想要跟踪用户,但只能在实时系统上,不在你的开发系统上。 Tracking类需要一个实时配置,但如果它不是实时配置,则会中止(不受影响)。
您的班级const
不是最好的,因为const
意味着您不想更改变量。不要将变量用于可能更改的值。你不应该使用静态的东西,因为它大多与依赖注入冲突。传递实物!
您的函数public static function getValueDependingOnURL()
应放置在Helper类中,而不是放在Constant/Configuration容器中。
class Helper
{
protected $config;
public function __construct(\Configuration $config) {
$this->config = $config;
return $this;
}
public function getValueByUrl($url) {
if ($url == 'something') {
return $config->getMinValue();
} else {
return $config->getMaxValue();
}
}
}
现在你可以有多个不同的配置,其助手类依赖于:
$config = new ConfigurationLive;
$helper = new Helper($config);
$value = $helper->getValueByUrl($_SERVER['REQUEST_URI']);
有大量的最佳实践设计模式的东西,代码风格和OOP在我的例子,了解这些信息,你将获得比你的问题的读者更高的软件工程水平。祝你好运!
为什么要有静态方法?常量:: MIN_VALUE将完全相同。 – vascowhite
@vascowhite请参阅编辑 – Pattle
这没有任何意义。 – vascowhite