萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 靜態頁面生成類實現靜態化緩存

靜態化是提升高並發頁面性能的經典手段:將動態 PHP 頁面生成為靜態 HTML 文件,後續請求直接由 Web 服務器(Nginx/Apache)靜態文件服務,繞過 PHP 執行。本文提供一個 StaticGenerator 類,支援分類存儲、自動創建目錄、內容捕獲、增量更新。

類設計

class StaticGenerator {
    private $htmlRoot;      // 靜態文件根目錄
    private $monthSubDir;   // 按月子目錄
    private $listDir;       // 列表頁目錄
    private $content = '';
    private $fileName = '';
    private $ext = '.html';

    public function __construct(string $htmlRoot = '') {
        $this->htmlRoot = $htmlRoot ?: sys_get_temp_dir() . '/static_html/';
        $this->monthSubDir = date('Y/m/');
        $this->listDir = 'list/';
    }

    // 設置生成參數
    public function createHtml(string $type, string $destName, string $content): self {
        // 確保目錄存在
        foreach ([$this->htmlRoot, $this->htmlRoot.$this->monthSubDir, $this->htmlRoot.$this->listDir] as $dir) {
            if (!is_dir($dir)) mkdir($dir, 0755, true);
        }

        switch ($type) {
            case 'index':  $this->fileName = $destName; break;
            case 'list':   $this->fileName = $this->listDir . $destName; break;
            case 'view':   $this->fileName = $this->monthSubDir . $destName; break;
            default:       throw new InvalidArgumentException("未知類型: $type");
        }
        $this->fileName .= $this->ext;
        $this->content = $content;
        return $this;
    }

    // 寫入文件
    public function write(): string|false {
        $fullPath = $this->htmlRoot . $this->fileName;
        // 原子寫入:先寫臨時文件再重命名,防止讀取到半寫文件
        $tmpPath = $fullPath . '.tmp.' . uniqid();
        if (file_put_contents($tmpPath, $this->content, LOCK_EX) === false) {
            @unlink($tmpPath);
            return false;
        }
        if (!rename($tmpPath, $fullPath)) {
            @unlink($tmpPath);
            return false;
        }
        return $fullPath;
    }

    // 刪除靜態文件
    public function delete(string $type, string $destName): bool {
        $path = $this->htmlRoot;
        switch ($type) {
            case 'index': $path .= $destName; break;
            case 'list':  $path .= $this->listDir . $destName; break;
            case 'view':  $path .= $this->monthSubDir . $destName; break;
        }
        $path .= $this->ext;
        return file_exists($path) ? unlink($path) : true;
    }

    // 判斷是否需要重新生成(基於修改時間)
    public function needsRegenerate(string $type, string $destName, int $ttlSeconds = 3600): bool {
        $path = $this->htmlRoot;
        switch ($type) {
            case 'index': $path .= $destName; break;
            case 'list':  $path .= $this->listDir . $destName; break;
            case 'view':  $path .= $this->monthSubDir . $destName; break;
        }
        $path .= $this->ext;
        if (!file_exists($path)) return true;
        return (time() - filemtime($path)) > $ttlSeconds;
    }
}

使用示例

<?php
require 'StaticGenerator.php';

$gen = new StaticGenerator('/var/www/html/static/');

// 情況 1:首頁靜態化(1 小時更新一次)
if ($gen->needsRegenerate('index', 'index', 3600)) {
    ob_start();
    // 動態生成首頁內容(查詢數據庫、渲染模板...)
    include 'templates/home.php';
    $content = ob_get_clean();
    $gen->createHtml('index', 'index', $content)->write();
}

// 情況 2:文章詳情頁(按需生成,永久緩存,發布/更新時手動刪除)
$articleId = 123;
if ($gen->needsRegenerate('view', "article_{$articleId}", 86400*365)) { // 1 年
    // 獲取文章數據...
    $content = renderArticle($articleId);
    $gen->createHtml('view', "article_{$articleId}", $content)->write();
}

// 情況 3:列表頁分頁靜態化
$page = 2;
if ($gen->needsRegenerate('list', "category_5_page_{$page}", 1800)) { // 30 分鐘
    $content = renderCategoryList(5, $page);
    $gen->createHtml('list', "category_5_page_{$page}", $content)->write();
}

// 後台發布/編輯文章時,刪除對應靜態文件觸發重新生成
// $gen->delete('view', "article_{$articleId}");

Nginx 配置優先靜態文件

server {
    root /var/www/html/static;
    index index.html;

    location / {
        # 嘗試直接服務靜態文件,不存在則轉發給 PHP
        try_files $uri $uri/ /index.php$is_args$args;
    }

    location ~ \.php$ {
        fastcgi_pass unix:/run/php/php8.1-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

進階策略

  • 邊緣緩存 (CDN):靜態文件推送至 CDN,源站僅作生成源。
  • 碎片化靜態化 (ESI/SSI):頁面中動態部分(用戶信息、購物車)用 ESI/SSI 標籤或 AJAX 載入,其餘靜態化。
  • 增量更新:監聽數據庫 Binlog 或發布事件,精確失效相關靜態文件,而非全站重建。
  • 壓縮預生成:生成時同步產出 .gz、.br,Nginx gzip_static on; brotli_static on; 直接服務壓縮文件。
  • 多版本管理:保留最近 N 個版本,支援一鍵回滾。

注意事項

  • 文件權限:Web 服務器用戶需有目錄寫入權限(chown www-data:www-data static/ -R)。
  • 并發生成:高併發下同一文件可能被多進程同時生成,建議用文件鎖(flock)或 Redis 分佈式鎖串行化。
  • 清理策略:定期掃描刪除過期、孤兒靜態文件,防止磁盤佔滿。
  • 動態參數:靜態頁面中避免直接輸出 Session/CSRF Token 等用戶態數據,改用 JS 從 API 獲取。

靜態化是「以空間換時間、以預計算換實時計算」的經典架構模式,StaticGenerator 類提供了結構化的生成、失效、刪除能力,可作為 CMS、電商、門戶站點靜態化基礎設施的核心組件。

copyright © 萬盛學電腦網 all rights reserved