首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP mysqli 資料庫類:支援快取、鏈式操作與多種查詢模式

     編輯:PHP 綜合知識

類別設計概覽

這是一個功能完整的 db_mysqli 類,封裝了 MySQLi 擴展,提供了快取機制、多種查詢介面、自動資源管理等特性。適合中小型專案快速開發使用。

核心特性

  • 連線管理:建構子自動連線、設定 UTF-8、失敗時輸出錯誤並終止
  • 資源自動釋放:解構子自動釋放結果集、關閉連線
  • 快取支援:可配置快取目錄、過期時間,支援單行、多行、單值快取
  • 多種查詢模式:getOne、getRow、getAll 及對應快取版本
  • LIMIT 自動補全:查詢方法支援選擇性 LIMIT 參數
  • 防注入轉義:escape() 方法支援陣列批量轉義

完整類別代碼

mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
        if (mysqli_connect_errno()) {
            $this->mysqli = false;
            echo '

' . mysqli_connect_error() . '

'; die(); } else { $this->mysqli->set_charset("utf8"); } } public function __destruct() { $this->free(); $this->close(); } protected function free() { @$this->rs->free(); } protected function close() { $this->mysqli->close(); } protected function fetch() { return $this->rs->fetch_array($this->fetch_mode); } protected function getQuerySql($sql, $limit = null) { if (@preg_match("/[0-9]+(,[ ]?[0-9]+)?/is", $limit) && !preg_match("/ LIMIT [0-9]+(,[ ]?[0-9]+)?$/is", $sql)) { $sql .= " LIMIT " . $limit; } return $sql; } protected function get_cache($sql, $method) { include_once './cache.php'; $cache = new cache($this->cache_dir, $this->cache_time); $cache_file = md5($sql . $method); $res = $cache->get_cache($cache_file); if (!$res) { $res = $this->$method($sql); $cache->set_cache($cache_file, $res); } return $res; } public function query_num() { return $this->query_num; } public function set_cache_dir($cache_dir) { $this->cache_dir = $cache_dir; } public function set_cache_time($cache_time) { $this->cache_time = $cache_time; } public function query($sql, $limit = null) { $sql = $this->getQuerySql($sql, $limit); $this->sql = $sql; $this->rs = $this->mysqli->query($sql); if (!$this->rs) { echo "

" . $this->mysqli->error . "

"; die(); } else { $this->query_num++; return $this->rs; } } public function getOne($sql) { $this->query($sql, 1); $this->fetch_mode = MYSQLI_NUM; $row = $this->fetch(); $this->free(); return $row[0]; } public function get_one($sql) { return $this->getOne($sql); } public function cache_one($sql) { $sql = $this->getQuerySql($sql, 1); return $this->get_cache($sql, 'getOne'); } public function getRow($sql, $fetch_mode = MYSQLI_ASSOC) { $this->query($sql, 1); $this->fetch_mode = $fetch_mode; $row = $this->fetch(); $this->free(); return $row; } public function get_row($sql, $fetch_mode = MYSQLI_ASSOC) { return $this->getRow($sql); } public function cache_row($sql) { $sql = $this->getQuerySql($sql, 1); return $this->get_cache($sql, 'getRow'); } public function getAll($sql, $limit = null, $fetch_mode = MYSQLI_ASSOC) { $this->query($sql, $limit); $all_rows = array(); $this->fetch_mode = $fetch_mode; while ($rows = $this->fetch()) { $all_rows[] = $rows; } $this->free(); return $all_rows; } public function get_all($sql, $limit = null, $fetch_mode = MYSQLI_ASSOC) { return $this->getAll($sql); } public function cache_all($sql, $limit = null) { $sql = $this->getQuerySql($sql, $limit); return $this->get_cache($sql, 'getAll'); } public function insert_id() { return $this->mysqli->insert_id(); } public function escape($str) { if (is_array($str)) { foreach ($str as $key => $val) { $str[$key] = $this->escape($val); } } else { $str = addslashes(trim($str)); } return $str; } }

使用範例

set_cache_time(10);           // 10 秒快取
$db->set_cache_dir('./cache/sql/'); // 自訂快取目錄

$sql = "SELECT * FROM words ORDER BY word_id LIMIT 10,10";

// 一般查詢(每次都查資料庫)
$res1 = $db->get_all($sql);

// 快取查詢(首次查資料庫,後續讀快取)
$res2 = $db->cache_all($sql);

// 查看實際查詢次數
echo $db->query_num() . '
'; // 輸出 1(第二次走快取) ?>

快取機制說明

快取鍵值 = md5($sql . $method),其中 $method 為 getOne、getRow、getAll 之一。這意味著:

  • 相同 SQL 不同查詢方法會產生不同快取
  • 快取檔案儲存在 $cache_dir 目錄下
  • 過期時間由 $cache_time 控制(秒)

改進建議與注意事項

🔧 現代化改進方向

  1. 使用 Prepared Statements:現有 escape() 使用 addslashes 不夠安全,應改用 mysqli::prepare + bind_param
  2. 依賴注入 Cache 類:避免在類內部 include_once,改為建構子注入 CacheInterface
  3. 例外處理:將 die() 改為拋出 Exception,由上層統一處理
  4. 支援交易:新增 beginTransaction()、commit()、rollback()
  5. 移除已棄用別名:get_one、get_row、get_all 建議棄用,統一駝峰命名

適用場景

  • ✅ 快速原型開發、中小型專案
  • ✅ 需要簡單頁面級快取的傳統 PHP 專案
  • ❌ 高併發、大數據量、強一致性要求的系統
  • ❌ 現代框架專案(Laravel、Symfony 等已有完善 ORM)

這個類別展示了 PHP 面向對象封裝資料庫操作的經典模式,理解其設計思路有助於掌握資料存取層的核心概念。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved