流介面模式
想必大部分人看到這個流介面模式一臉懵,但是在我們日常開發中使用的再頻繁不過了,
舉個例子一眼看明白
(new Model())->select(['id', 'name'])->where(['name' => 'test']);
實現程式碼
class Model
{
private $where = [];
private $fields = [];
public function where(string $condition)
{
$this->where[] = $condition;
return $this;
}
public function select(array $fields)
{
$this->fields = $fields;
return $this;
}
public function __toString()
{
return sprintf(
'SELECT %S FROM test WHERE %s',
join(', ', $this->fields),
join(' AND', $this->where)
);
}
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結