Reputation: 5957
I've the following class (simplified here, and so not tested):
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);
}
}
The child method just adds SQL conditions to the parent's query, and then execute the request. But the DB call is redundent, and requires an if
statment into the parent method.
So I would like to know the recommended way to do it?
I imagine something like that, but I don't know how to do it:
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);
}
}
Maybe it's impossible, or maybe there is a better design pattern to do it?
Upvotes: 0
Views: 91
Reputation: 8652
You can use abstractions, that way you can override parent method with child code and it will be called
you can read about it 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";
}
}
Upvotes: 2