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

PHP 緩存操作類完整實現與應用詳解

     編輯:PHP 相關知識

在高併發場景下,資料庫查詢、Web Service 呼叫等 I/O 操作往往成為效能瓶頸。雖然 APC、Zend Optimizer 等擴展能顯著提升效能,但虛擬主機環境常無法安裝。此時,自行實現 PHP 檔案級緩存類成為實用方案。

緩存類核心功能

  • 讀取緩存:支援指定有效期、自動檢測過期並刪除
  • 寫入緩存:支援陣列/物件序列化存儲,自動建立目錄權限
  • 刪除指定緩存:依 ID 精準清除
  • 清空所有緩存:遞歸刪除緩存目錄下所有文件

完整類代碼

<?php
class Cache {
    protected $options = [];
    protected $cacheCount = 0;
    protected $cacheTime = 60;
    protected $cachePath = 'cache/';
    protected $returnType = 1; // 1=陣列, 2=物件

    public function readCache($id, $time = 0, $path = '') {
        $id = md5($id);
        $this->cachePath = empty($path) ? $this->cachePath : $path;
        $this->cacheTime = empty($time) ? $this->cacheTime : $time;
        $file = $this->cachePath . $id . '.php';

        if (file_exists($file)) {
            // 檢查過期
            if ((filemtime($file) + $this->cacheTime) < time()) {
                @unlink($file);
                return null;
            }
            if ($this->returnType === 1) {
                return include $file;
            } else {
                $data = file_get_contents($file);
                return unserialize($data);
            }
        }
        return null;
    }

    public function writeCache($id, $data, $path = '') {
        $this->cacheCount++;
        $id = md5($id);
        $this->cachePath = empty($path) ? $this->cachePath : $path;
        $file = $this->cachePath . $id . '.php';
        @chmod($this->cachePath, 0777);

        if ($this->returnType === 1) {
            $data = '<?php return ' . var_export($data, true) . '; ?>';
        } else {
            $data = serialize($data);
        }
        return file_put_contents($file, $data);
    }

    public function delCache($id, $path = '') {
        $id = md5($id);
        $this->cachePath = empty($path) ? $this->cachePath : $path;
        $file = $this->cachePath . $id . '.php';
        if (file_exists($file)) {
            return unlink($file);
        }
        return null;
    }

    public function delAllCache($path = '') {
        $this->cachePath = empty($path) ? $this->cachePath : $path;
        $dir = $this->cachePath;
        if (is_dir($dir)) {
            $dh = opendir($dir);
            while (($file = readdir($dh)) !== false) {
                if ($file !== '..' && $file !== '.') {
                    $fullPath = $dir . '/' . $file;
                    if (is_dir($fullPath)) {
                        $this->delAllCache($fullPath);
                    } else {
                        @unlink($fullPath);
                    }
                }
            }
            closedir($dh);
        }
        return true;
    }
}

使用範例

<?php
include('cache.php');
$data = ['https://example.com', 'https://google.com', 'https://github.com'];
$cache = new Cache();
$id = 'test_links';

// 寫入緩存
$cache->writeCache($id, $data);

// 讀取緩存(120秒有效期)
$cached = $cache->readCache($id, 120);
print_r($cached);

// 刪除特定緩存
$cache->delCache($id);

// 清空所有緩存
$cache->delAllCache();

注意事項

  1. 確保 cache/ 目錄存在且可寫(權限 0777)
  2. 大量資料建議改用 Redis/Memcached 等記憶體級緩存
  3. 生產環境需考慮緩存穿透、雪崩等問題
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved