我有以下课程(在此简化,因此未经测试):
class FATHER {
protected function getDatas() {
$this->query = "SELECT * FROM somewhere WHERE year = ? AND id_smthg = ? ";
$this->param = array($_GET['year'], $_SESSION['anId']);
// if $this is a FATHER
if (get_called_class() == get_class())
DB::getDatas($this->query, $this->$params);
}
}
class CHILD extends FATHER {
protected function getDatas() {
parent::getDatas();
foreach ($this->conditions as $condition) {
$this->query .= " AND $condition->name = ? ";
$this->param .= array($condition->value);
}
DB::getDatas($this->query, $this->params);
}
}
子方法只是将SQL条件添加到父查询中,然后执行请求。但是DB调用是redundent,并且需要在父方法中使用if
语句。
所以我想知道推荐的方法吗?
我想像这样的东西,但我不知道该怎么做:
class FATHER {
protected function getDatas() {
$this->query = "SELECT * FROM somewhere WHERE year = ? AND id_smthg = ? ";
$this->param = array($_GET['year'], $_SESSION['anId']);
// Make the child execution here
DB::getDatas($this->query, $this->$params);
}
}
也许这是不可能的,或者可能有更好的设计模式来做到这一点?
答案 0 :(得分:2)
您可以使用抽象,这样您可以使用子代码覆盖父方法,并将其称为
你可以阅读here
abstract class AbstractClass
{
// Force Extending class to define this method
abstract protected function getValue(); //this kind of methods you should implement in child
abstract protected function prefixValue($prefix);
// Common method
public function printOut() {
print $this->getValue() . "\n";
}
}