我正在一个项目中,例如,在一个名为“常量”的类中定义了所有全局常量的项目
class Constants
{
const MIN_VALUE = 0.0;
const MAX_VALUE = 1.0;
public static function getMinValue()
{
return self::MIN_VALUE;
}
public static function getMaxValue()
{
return self::MAX_VALUE;
}
public static function getValueDependingOnURL()
{
if($_SERVER['REQUEST_URI'] == 'something')
{
return self::MIN_VALUE;
}
else
{
return self::MAX_VALUE;
}
}
}
然后在整个代码Constants::getMaxValue()
中使用类似的东西来获取常量的值。这似乎是一种非常奇怪的方法,为什么您不只define
在最外部的作用域中使用该函数?我知道define()
速度可能很慢,但是肯定必须调用类属性也不是最有效的方法吗?
编辑:还有一些函数在其中有条件,因此为什么要调用函数
弄清问题:与全局define()
配置的内容相比,配置容器的优点是什么?
优点是OOP提供的所有优点:数据抽象和封装,继承,多态性和更好的设计模式集成。
该主题的读者似乎有些困惑,专注于您的课程而不是主要问题。为了澄清这一点,让我举一个例子:
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();
}
}
}
现在,您可以拥有helper类所依赖的不同配置集:
$config = new ConfigurationLive;
$helper = new Helper($config);
$value = $helper->getValueByUrl($_SERVER['REQUEST_URI']);
在我的示例中,有很多最佳实践设计模式的内容,代码风格和OOP,了解这些内容后,您将获得比问题读者更高的软件工程水平。祝好运!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句