如何避免重复的代码?
问题描述:
我有以下问题,我的SQLBuilder的那些方法是一样的,我可以做些什么来减少代码?如何避免重复的代码?
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;
}
答
创建一个具有处理和使用他们
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;
}
答
或
public function action($data, $type){
if(is_array($data)){
$this->$type = implode(',', $data);
} else {
$this->$type = $data;
}
return $this;
}
然后
$this->action($data, 'select');
HTTP则公共方法常见的私有方法://计算器.com/questions/108699/good-php-orm-library –
https://en.wikipedia.org/wiki/Code_refactoring –
将所有代码从' - > from'更改为' - > select'?正如杰里米所说的那种被称为重构的东西。搜索和替换所有将成为你最好的朋友,除非你碰巧使用了一个体面的IDE与良好的重构内置(提示PHP没有一个) – Dave