流式接口 通過方法返回 $this 實現 鏈式調用:
$query->where('status', 1)->orderBy('id', 'desc')->limit(10)->get();
優勢:代碼閱讀如自然語言、減少中間變量、參數順序固化、IDE 自動補全友好。
public function where(...): selfpublic function get(): Collection<?php
class QueryBuilder {
protected array $wheres = [];
protected array $orders = [];
protected ?int $limit = null;
protected ?int $offset = null;
protected string $table;
public function __construct(string $table) {
$this->table = $table;
}
// 修改器:返回 $this
public function where(string $column, mixed $value, string $operator = '='): self {
$this->wheres[] = compact('column', 'operator', 'value');
return $this;
}
public function orWhere(string $column, mixed $value, string $operator = '='): self {
$this->wheres[] = ['type' => 'or', ...compact('column', 'operator', 'value')];
return $this;
}
public function orderBy(string $column, string $direction = 'asc'): self {
$this->orders[] = compact('column', 'direction');
return $this;
}
public function limit(int $limit): self {
$this->limit = $limit;
return $this;
}
public function offset(int $offset): self {
$this->offset = $offset;
return $this;
}
// 終結器:執行並返回結果
public function get(): array {
$sql = $this->toSql();
// 實際執行 PDO...
return $this->execute($sql);
}
public function first(): ?array {
$this->limit(1);
$results = $this->get();
return $results[0] ?? null;
}
public function count(): int {
// SELECT COUNT(*) ...
return 0;
}
private function toSql(): string {
$sql = "SELECT * FROM `{$this->table}`";
if ($this->wheres) {
$conditions = [];
foreach ($this->wheres as $i => $w) {
$prefix = ($w['type'] ?? 'and') === 'or' ? 'OR' : 'AND';
if ($i === 0) $prefix = 'WHERE';
$conditions[] = "{$prefix} `{$w['column']}` {$w['operator']} ?";
}
$sql .= ' ' . implode(' ', $conditions);
}
if ($this->orders) {
$sql .= ' ORDER BY ' . implode(', ', array_map(
fn($o) => "`{$o['column']}` {$o['direction']}", $this->orders
));
}
if ($this->limit) {
$sql .= " LIMIT {$this->limit}";
if ($this->offset) $sql .= " OFFSET {$this->offset}";
}
return $sql;
}
private function execute(string $sql): array {
// 實際連接數據庫執行...
return [];
}
}
// 使用
$users = (new QueryBuilder('users'))
->where('status', 1)
->where('role', 'admin')
->orderBy('created_at', 'desc')
->limit(10)
->get();
ThinkPHP 核心 Model 類正是採用此模式:
// 簡化版 Model.class.php 核心片段
class Model {
protected array $options = []; // 累積查詢選項
public function join(string $join): self {
$this->options['join'] = $join;
return $this;
}
public function where(mixed $where): self {
$this->options['where'] = $where;
return $this;
}
public function order(string $order): self {
$this->options['order'] = $order;
return $this;
}
public function limit(mixed $limit): self {
$this->options['limit'] = $limit;
return $this;
}
public function select(): array {
// 1. 根據 $this->options 構建 SQL
// 2. 執行查詢
// 3. 重置 $this->options = [] (重要!避免污染下次查詢)
// 4. 返回結果集
return $resultSet;
}
}
public function select(): array {
$sql = $this->buildSelectSql();
$result = $this->db->query($sql);
$this->options = []; // 🔑 重置,否則下次調用會攜帶上次條件
return $result;
}
Eloquent/Doctrine 採用 不可變模式:每次修改返回 新實例**。
class ImmutableQueryBuilder {
// ... 屬性同前
public function where(string $column, mixed $value, string $operator = '='): self {
$clone = clone $this;
$clone->wheres[] = compact('column', 'operator', 'value');
return $clone;
}
// 其他修改器同理 clone 後修改返回
}
優勢**:線程安全、可緩存中間狀態、並發安全(Swoole 協程環境必備)。
劣勢**:內存開銷大、GC 壓力大。
| 陷阱 | 後果 | 修正 |
|---|---|---|
| 忘記返回 $this | 鏈式中斷,報錯「Call to member function on null」 | 所有修改器強制 : self 返回類型聲明 |
| 不重置內部狀態 | 第二次查詢攜帶第一次條件,產生錯誤 SQL | 終結器執行前 $this->reset() |
| 修改器做了 I/O 操作 | 違反單一職責,難以測試 | 修改器只構建狀態,終結器執行 I/O |
| 過度鏈式導致可讀性下降 | 一行 200 字符無法維護 | 適當換行、提取變量、拆分方法 |
$user->setName()->setEmail() 反而降低可讀性)$order->pay()->ship()->complete() 應用服務層處理)流式接口通過 「修改器返回 $this,終結器返回結果」 實現鏈式調用。ThinkPHP Model 類是經典實踐:options 陣列累積狀態,select() 終結執行並重置。掌握 狀態累積 → 終結執行 → 狀態重置** 三步曲,即可設計出優雅、可測試、IDE 友好的 API。