我刚开始学习PHP OOP,以前我一直在以程序方式进行PHP操作。我读this article和我有几个简单的问题,PHP OOP概念(值对象/数据访问对象)
如何通常被定义为值对象的构造?作为一个接受所有“数据成员”作为参数或坚持默认构造函数并使用mutator/accessor方法设置/获取数据成员的方法?
这实际上是开始做PHP OOP的推荐方式吗?诚实地说,文章中解释的概念对我来说有点混乱。
干杯
我刚开始学习PHP OOP,以前我一直在以程序方式进行PHP操作。我读this article和我有几个简单的问题,PHP OOP概念(值对象/数据访问对象)
如何通常被定义为值对象的构造?作为一个接受所有“数据成员”作为参数或坚持默认构造函数并使用mutator/accessor方法设置/获取数据成员的方法?
这实际上是开始做PHP OOP的推荐方式吗?诚实地说,文章中解释的概念对我来说有点混乱。
干杯
要建立充当中立的数据容器,我会用经典的构造__contruct()
然后你可以使用魔法__get
和__set
访问属性的对象。 另一种方式在通过谷歌搜索“依赖注入”注入具有例如,你可以找到更多这方面的信息DB行对象数据
你可以启动它在通过一个主类最OOP语言,但对网络的关注MVC被广泛使用。
您是否有以前的OOP编程经验?
对象必须始终处于有效的状态。这意味着对象总是表现(方法)并包含有意义的信息(成员变量)。构造函数的目的是创建处于有效状态的对象。
考虑到值对象,构造函数必须采用最少数量的参数,以便该对象有意义。例如,如果你有一个RGB值对象,如果红色是字符串“猴子”,绿色是NULL,蓝色是数组,那么在你的应用程序中是否有意义?
final class RGB {
$r, $g, $b;
}
$mycolor = new RGB;
// NULL, what value of red is that supposed to be?
var_dump($mycolor->r);
// We are free to set these values too, even though they do not make sense.
$mycolor->r = 'monkey';
$mycolor->g = NULL;
$mycolor->b = array('foo', 'bar');
这正是这个对象允许发生的情况。 $ mycolor引用一个不处于有效状态的对象。我们如何确保RGB对象始终具有三个值,即红色,蓝色和绿色,并且它们都是0到255之间的数字?
final class RGB {
private $r;
private $g;
private $b;
public function __construct($r, $g, $b) {
// are our arguments numbers?
if (!is_numeric($r)) {
throw new Exception('Value of red must be a number');
}
if (!is_numeric($g)) {
throw new Exception('Value of green must be a number');
}
if (!is_numeric($b)) {
throw new Exception('Value of blue must be a number');
}
// are our arguments within range 0-255?
if ($r < 0 || $r > 255) {
throw new Exception('Value of red must be 0-255');
}
if ($g < 0 || $g > 255) {
throw new Exception('Value of green must be 0-255');
}
if ($b < 0 || $b > 255) {
throw new Exception('Value of blue must be 0-255');
}
// our arguments are fine.
$this->r = $r;
$this->g = $g;
$this->b = $b;
}
//*// Canadian support
public function getColour() {
return $this->getColor();
}
public function getColor() {
return array($this->r, $this->g, $this->b);
}
}
$mycolor = new RGB; // error! missing three arguments
$mycolor->r = 'monkey'; // error! this field is private
// exception! the constructor complains about our values not being numbers
$mycolor2 = new RGB('monkey', NULL, array('foo', 'bar'));
// exception! the constructor complains our numbers are not in range
$mycolor3 = new RGB(300, 256, -10);
$mycolor4 = new RGB(255, 0, 0); // ahh... a nice shade of red
var_dump($mycolor4->getColor()); // we can read it out later when we need to
如果你的构造函数需要三个参数,除非所有三个是数字0和255之间,你将永远被定义与良好的价值观成员变量,它抛出一个异常。
您还必须确保红色,蓝色和绿色成员变量是私人的。否则,任何人都可以写任何他们想要的东西。当然,如果他们是私人的,任何人都无法阅读。为了创建一个只读操作,我们定义了访问私有成员变量的getColor()方法。
此版本的RGB对象将始终具有有效状态。
希望这可以让我们了解面向对象的本质并给你一个开始思考的地方。
我从来没有在PHP上下文中看到过这些建议。 PHP程序员往往非常青睐MVC。该页面上的几条建议值得商榷,并不代表流行观点。 – 2010-04-29 14:04:54
*(替代阅读)* http://carsonified.com/blog/dev/getting-started-with-oop-php5/ – Gordon 2010-04-29 14:47:08
DAO模式是一种可以处理MVC模式中M层的一部分的方法。 DAO不是MVC的替代品。 – 2010-06-18 17:09:37