清晰化问题:配置容器相对于全局定义(define())的配置常量有什么优势?
这些优势都是面向对象编程提供的优势:数据抽象和封装,继承,多态以及更好的设计模式集成。
本帖的读者似乎有点困惑,把焦点放在了你的类上而不是主要问题上。为了进一步澄清这一点,让我举个例子:
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'])
我的例子中有很多最佳实践的设计模式、代码风格和面向对象编程,学习这些内容会让你比提问者拥有更高水平的软件工程能力。祝你好运!