简体   繁体   中英

Concrete Methods in Interface Classes

I am building some classes (in PHP, although this question extends to other OOP languages as well) which hold information from a database. As such, I want to create an Interface: "syncable".

interface syncable{
  protected function _pushToDB();
  protected function _pullFromDB();
}

The problem I am encountering is that I want "syncable" to also have a method which (probably) never changes and variable to go with:

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;
  }
}

As variables are changed in an implemented class, or the database is updated elsewhere, the $sync variable is updated to properly reflect the type of sync needed, then sync() can be called at some point which in turn calls the proper implemented method. While _pushToDB() and _pullFromDB() are very specialized per class, sync() will remain constant between most, if not all, classes.

Since the classes implementing "syncable" such as "users", "foo", and "bar" have no real relation to "syncable" and may need to extend other classes, "syncable" should be an interface rather than an abstract class.

So my question is, what is the best way of accomplishing this? Must I copy-paste my sync() function into every class which implements "syncable"? Do I create an abstract class and hope no class which extends "syncable" ever needs to extend anything else? (Since PHP and many OOP don't support multiple-inheritance) Is there some other PHP solution which would better fit this situation? Are there any generic OOP solutions for this problem?

You should have a look at php traits , you can create this traits and then use them whereever you want/need to use them, is a part of the multi-inheritance principle:

http://php.net/manual/en/language.oop5.traits.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM