新浪雲平台(SAE)原生 SaeMysql 類功能有限、耦合度高。為解決「無完整 CRUD、全域變量污染、遷移困境」三大痛點,作者封裝 kuigg_Db 靜態類,實現鏈式調用、表前綴自動化、零實例化調用,並為未來遷移預留介面。本文深度解析設計思路與核心代碼。
SaeMysql 僅提供 runSql(),插入/更新/刪除需手寫完整 SQL,易出錯且難維護。global $mysql 傳遞實例,污染命名空間,單元測試困難。private static $instance;
public static function &instance() {
if (empty(self::$instance)) self::$instance = new SaeMysql();
return self::$instance;
}
kuigg_Db::method() 靜態調用,語法簡潔。public static function tableName($table) {
return "kuigg_{$table}"; // 可配置化、環境感知
}
| 操作 | 方法簽名 | 回傳值 | 示例 |
|---|---|---|---|
| 新增 | insert($table, $data, $getInsertId=false, $replace=false) | bool / insert_id | kuigg_Db::insert('user', ['name'=>'Tom', 'email'=>'tom@ex.com'], true) |
| 刪除 | delete($table, $where=null, $getAffectedRows=false, $limit=0) | bool / affected_rows | kuigg_Db::delete('user', "`id`=1", true) |
| 修改 | update($table, $data, $where=null, $getAffectedRows=false, $lowPriority=false) | bool / affected_rows | kuigg_Db::update('user', ['name'=>'Jerry'], "`id`=1", true) |
| 查詢多行 | fetchData($table, $fields='*', $where='') | 二維陣列 | kuigg_Db::fetchData('user', '*', "`status`=1 ORDER BY id DESC LIMIT 10") |
| 查詢單行 | fetchRow($table, $fields='*', $where='') | 一維陣列 | kuigg_Db::fetchRow('user', '*', "`id`=1") |
| 查詢單值 | fetchItem($table, $field, $where='') | 標量 | kuigg_Db::fetchItem('user', 'email', "`id`=1") |
| 統計筆數 | count($table, $fields='*', $where='') | 整數 | kuigg_Db::count('user', '*', "`status`=1") |