接口中的具体方法 类
Concrete Methods in Interface Classes
我正在构建一些 classes(在 PHP 中,尽管这个问题也扩展到其他 OOP 语言),它们保存来自数据库的信息。因此,我想创建一个接口:"syncable".
interface syncable{
protected function _pushToDB();
protected function _pullFromDB();
}
我遇到的问题是我希望 "syncable" 也有一个(可能)永远不会改变的方法和变量:
protected $sync = 0;
public function sync(){
if($this->sync == 0){
// DB in sync with class; Do nothing.
}
if(this->sync == 1){
$this->_pushToDB();
$this->sync = 0;
}
if(this->sync == -1){
$this->_pullFromDB();
$this->sync = 0;
}
}
当变量在已实现的 class 中发生变化,或者数据库在别处更新时,$sync 变量会更新以正确反映所需的同步类型,然后可以在某个时候调用 sync()依次调用正确的实现方法。虽然 _pushToDB() 和 _pullFromDB() 根据 class 非常专业,但 sync() 将在大多数(如果不是全部)class 之间保持不变。
因为 class 实现 "syncable" 的 "users"、"foo" 和 "bar" 与 "syncable" 和 "syncable" 没有实际关系可能需要扩展其他 classes,"syncable" 应该是一个接口而不是抽象 class.
所以我的问题是,完成此任务的最佳方法是什么?我必须将我的 sync() 函数复制粘贴到每个实现 "syncable" 的 class 中吗?我是否创建了一个抽象 class 并希望扩展 "syncable" 的 class 不需要扩展其他任何东西? (因为 PHP 和许多 OOP 不支持多重继承)是否有其他一些 PHP 解决方案更适合这种情况?这个问题有任何通用的 OOP 解决方案吗?
你应该看看 php traits
,你可以创建这个特征,然后在任何地方使用它们 want/need 使用它们,是多重继承原则的一部分:
我正在构建一些 classes(在 PHP 中,尽管这个问题也扩展到其他 OOP 语言),它们保存来自数据库的信息。因此,我想创建一个接口:"syncable".
interface syncable{
protected function _pushToDB();
protected function _pullFromDB();
}
我遇到的问题是我希望 "syncable" 也有一个(可能)永远不会改变的方法和变量:
protected $sync = 0;
public function sync(){
if($this->sync == 0){
// DB in sync with class; Do nothing.
}
if(this->sync == 1){
$this->_pushToDB();
$this->sync = 0;
}
if(this->sync == -1){
$this->_pullFromDB();
$this->sync = 0;
}
}
当变量在已实现的 class 中发生变化,或者数据库在别处更新时,$sync 变量会更新以正确反映所需的同步类型,然后可以在某个时候调用 sync()依次调用正确的实现方法。虽然 _pushToDB() 和 _pullFromDB() 根据 class 非常专业,但 sync() 将在大多数(如果不是全部)class 之间保持不变。
因为 class 实现 "syncable" 的 "users"、"foo" 和 "bar" 与 "syncable" 和 "syncable" 没有实际关系可能需要扩展其他 classes,"syncable" 应该是一个接口而不是抽象 class.
所以我的问题是,完成此任务的最佳方法是什么?我必须将我的 sync() 函数复制粘贴到每个实现 "syncable" 的 class 中吗?我是否创建了一个抽象 class 并希望扩展 "syncable" 的 class 不需要扩展其他任何东西? (因为 PHP 和许多 OOP 不支持多重继承)是否有其他一些 PHP 解决方案更适合这种情况?这个问题有任何通用的 OOP 解决方案吗?
你应该看看 php traits
,你可以创建这个特征,然后在任何地方使用它们 want/need 使用它们,是多重继承原则的一部分: