靜態化是提升高並發頁面性能的經典手段:將動態 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}");
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;
}
}
.gz、.br,Nginx gzip_static on; brotli_static on; 直接服務壓縮文件。chown www-data:www-data static/ -R)。flock)或 Redis 分佈式鎖串行化。靜態化是「以空間換時間、以預計算換實時計算」的經典架構模式,StaticGenerator 類提供了結構化的生成、失效、刪除能力,可作為 CMS、電商、門戶站點靜態化基礎設施的核心組件。