I've the following Problem, those methods of my SQLBuilder are simply the same, what can I do to reduce the code?
public function select($fields){
if(is_array($fields)){
$this->fields = implode(',', $fields);
} else {
$this->fields = $fields;
}
return $this;
}
public function from($tables){
if(is_array($tables)){
$this->tables = implode(',', $tables);
} else {
$this->tables = $tables;
}
return $this;
}
create a common private method that does the processing and then public methods that use them
public function select($fields){
return $this->builddata($fields, 'fields');
}
public function from($tables){
return $this->builddata($tables, 'tables');
}
private function builddata($data, $storage) {
if(is_array($data)){
$data = implode(',', $data);
}
$this->$storage = $data; // variable variable
return $this;
}
or
public function action($data, $type){
if(is_array($data)){
$this->$type = implode(',', $data);
} else {
$this->$type = $data;
}
return $this;
}
then
$this->action($data, 'select');