2

我想实现继承,因为我按照这篇文章我没有得到数据库设计,我只能创建模型如下,我在模型/行为下创建了文件 InheritBehavior.php 和文章中一样。那么如何为这些模型设计数据库来支持继承

class Animal extends AppModel{
    var $name='Animal';
}

App::import('Model', 'Animal');
class Mammal extends Animal{
public $actsAs = array( 'Inherit' ); 
}   var $name= 'Mammal';

}


App::import('Model', 'Animal');
class Insect extends Animal{
    var $name='Insect';
}   

Animal: id, age
Mammal: id, no_of_legs ('age' is common)
Insect: id, no_of_wings ('age' is common)

什么是数据库设计(多表继承)。

对这种类型使用继承而不是关联(使用 hasOne 和 belongsTo)是个好主意吗? cakephp 会很好地支持吗?

4

1 回答 1

5

Sort answer: no, it is not a good idea.

In OOP it is recommended to always prefer composition over inheritance.


You are doing it wrong.

In OOP there is something we call Liskov substitution principle (for dumb down version: image). This means, that you should not remove or fundamentally change functionality, when sub-classing.

Also, using animals as OOP example always ends up horribly. Classify following: whale(no legs), bat(has wings), lice(no wings). I guess you see the problem.

And one other thing. As CakePHP user you might not be aware of it, but in PHP5 we have define variables as either private, public or protected. Instead of PHP4-style var.

于 2012-06-13T17:35:26.117 回答