PHP模式大全 - 流接口模式
流接口模式
想必大部分人看到这个流接口模式一脸懵,但是在我们日常开发中使用的再频繁不过了,
举个例子一眼看明白
(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 协议》,转载必须注明作者和本文链接