萬盛學電腦網

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

PHP 靜態頁面生成類:模板引擎與檔案快取實作

前言

早期 PHP 專案常用「靜態化」提升效能:將動態頁面預渲染為 HTML 檔案,Nginx/Apache 直接靜態服務,繞過 PHP 執行。本文分析一個經典 Shtml 靜態生成類,並提供現代化重構版本。

原始代碼分析 (PHP 4/5 風格)

<?php
class Shtml {
  var $Templet;      // 模板內容
  var $DataSource;   // 資料來源 (陣列)
  var $Dir;          // 輸出目錄
  var $fileName;     // 輸出檔名
  var $mod;          // 檔案模式 (wb)
  var $handle;       // 檔案控制代碼
  
  function Shtml($fileName = '') { // PHP 4 建構子
    $this->fileName = $fileName;
    $this->mod = 'wb';
    $this->handle = false;
    $this->Templet = '';
    $this->DataSource = [];
    $this->Dir = '';
  }
  
  function BindData($arr) { $this->DataSource = $arr; }
  function SetDir($dir) { $this->Dir = $dir; }
  function SetFileName($fileName) { return $this->fileName = $fileName; }
  
  // ... 後續方法:ParseTemplate(), CreateHtml(), WriteFile() 等
}

問題:var 關鍵字 (PHP 4)、無型別提示、無可見性控制、建構子命名耦合類名、手動檔案控制代碼管理、無錯誤處理、模板解析邏輯缺失。

現代化重構版 (PHP 8.1+)

<?php
declare(strict_types=1);

namespace App\StaticGenerator;

use RuntimeException;

/**
 * 靜態頁面生成器
 * 支援模板變數替換、區塊迴圈、條件判斷、繼承佈局
 */
final class StaticPageGenerator {
  private string $templateDir;
  private string $outputDir;
  private array $globals = [];
  
  public function __construct(string $templateDir, string $outputDir) {
    $this->templateDir = rtrim($templateDir, '/');
    $this->outputDir = rtrim($outputDir, '/');
    if (!is_dir($this->templateDir)) throw new RuntimeException("模板目錄不存在: {$this->templateDir}");
    if (!is_dir($this->outputDir)) {
      if (!mkdir($this->outputDir, 0755, true)) throw new RuntimeException("無法建立輸出目錄: {$this->outputDir}");
    }
  }
  
  /** 設定全域變數 (所有模板可用) */
  public function setGlobal(string $key, mixed $value): self {
    $this->globals[$key] = $value;
    return $this;
  }
  
  /** 批次設定全域變數 */
  public function setGlobals(array $vars): self {
    $this->globals = array_merge($this->globals, $vars);
    return $this;
  }
  
  /**
   * 生成靜態頁面
   * @param string $templateName 模板檔名 (相對 $templateDir)
   * @param string $outputFile   輸出檔名 (相對 $outputDir)
   * @param array  $data         頁面專用資料 (合併全域變數)
   * @return int 寫入位元組數
   */
  public function generate(string $templateName, string $outputFile, array $data = []): int {
    $templatePath = "{$this->templateDir}/{$templateName}";
    if (!is_file($templatePath)) throw new RuntimeException("模板不存在: {$templatePath}");
    
    $outputPath = "{$this->outputDir}/{$outputFile}";
    $outputDir = dirname($outputPath);
    if (!is_dir($outputDir) && !mkdir($outputDir, 0755, true)) {
      throw new RuntimeException("無法建立輸出子目錄: {$outputDir}");
    }
    
    // 合併資料:全域 + 頁面專用
    $vars = array_merge($this->globals, $data);
    
    // 渲染模板 (採用 PHP 原生模板語法,或整合 Twig/Blade)
    $content = $this->renderPhpTemplate($templatePath, $vars);
    
    // 原子性寫入:寫入暫存檔 → rename (避免讀取到半寫入檔案)
    $tempPath = $outputPath . '.tmp.' . bin2hex(random_bytes(8));
    $bytes = file_put_contents($tempPath, $content, LOCK_EX);
    if ($bytes === false) throw new RuntimeException("寫入暫存檔失敗: {$tempPath}");
    
    if (!rename($tempPath, $outputPath)) {
      @unlink($tempPath);
      throw new RuntimeException("原子性移動失敗: {$tempPath} -> {$outputPath}");
    }
    
    return $bytes;
  }
  
  /**
   * PHP 原生模板渲染 (極簡、無依賴、效能極佳)
   * 模板中可用:$var, $vars['key'], foreach, if, 
   * 提供 $this->escape() 防 XSS
   */
  private function renderPhpTemplate(string $templatePath, array $vars): string {
    // 提取變數至當前符號表
    extract($vars, EXTR_SKIP);
    
    // 防 XSS 輔助函數 (模板中可用 $this->e($str))
    $escape = function(string $str): string {
      return htmlspecialchars($str, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
    };
    
    // 捕獲輸出緩衝
    ob_start();
    try {
      include $templatePath;
      return ob_get_clean();
    } catch (Throwable $e) {
      ob_end_clean();
      throw $e;
    }
  }
  
  /** 批次生成 (如部落格文章列表) */
  public function generateBatch(string $templateName, string $outputPattern, iterable $items, callable $mapper): int {
    $totalBytes = 0;
    foreach ($items as $item) {
      [$outputFile, $data] = $mapper($item);
      $totalBytes += $this->generate($templateName, $outputFile, $data);
    }
    return $totalBytes;
  }
}

模板檔案範例 (PHP 原生語法)

<?php
// templates/article/detail.php
?><!DOCTYPE html>
<html lang="zh-TW">
<head>
  <meta charset="UTF-8">
  <title>e($title) ?> - 我的部落格</title>
  <meta name="description" content="e($excerpt) ?>">
</head>
<body>
  <header><h1>e($siteName) ?></h1></header>
  <main>
    <article>
      <h1>e($title) ?></h1>
      <time></time>
      <div class="content"></div> <!-- 已在控制器轉換為安全 HTML -->
    </article>
  </main>
  <footer>©  e($siteName) ?></footer>
</body>
</html>

控制器使用範例

<?php
// 生成首頁
$generator = new StaticPageGenerator(
  __DIR__ . '/../templates',
  __DIR__ . '/../public/static'
);
$generator->setGlobals([
  'siteName' => '我的部落格',
  'siteUrl' => 'https://example.com',
  'navItems' => ['首頁', '分類', '關於', '聯絡'],
])
->generate('index.php', 'index.html', [
  'articles' => $articleRepository->findLatest(10),
  'sidebarAds' => $adRepository->getActive(),
]);

// 批次生成文章詳情頁
$generator->generateBatch(
  'article/detail.php',
  'article/{id}.html',
  $articleRepository->findAllPublished(),
  fn($article) => [
    "article/{$article->getId()}.html",
    [
      'title' => $article->getTitle(),
      'excerpt' => $article->getExcerpt(),
      'content' => $article->getHtmlContent(),
      'createdAt' => $article->getCreatedAt()->getTimestamp(),
    ]
  ]
);

echo "靜態頁面生成完成\n";

進階:整合 Twig 模板引擎

<?php
// 使用 Twig 替代原生 PHP 模板
use Twig\Environment;
use Twig\Loader\FilesystemLoader;

class TwigStaticGenerator {
  private Environment $twig;
  private string $outputDir;
  
  public function __construct(string $templateDir, string $outputDir) {
    $loader = new FilesystemLoader($templateDir);
    $this->twig = new Environment($loader, [
      'cache' => false, // 靜態生成不需 Twig 快取
      'autoescape' => 'html',
      'strict_variables' => true,
    ]);
    $this->outputDir = $outputDir;
  }
  
  public function generate(string $template, string $outputFile, array $data = []): int {
    $content = $this->twig->render($template, $data);
    $outputPath = "{$this->outputDir}/{$outputFile}";
    $dir = dirname($outputPath);
    if (!is_dir($dir)) mkdir($dir, 0755, true);
    $temp = $outputPath . '.tmp.' . bin2hex(random_bytes(8));
    file_put_contents($temp, $content, LOCK_EX);
    rename($temp, $outputPath);
    return strlen($content);
  }
}

部署自動化:CI/CD 整合

# .github/workflows/static-deploy.yml
name: Deploy Static Pages
on:
  push:
    branches: [main]
  schedule:
    - cron: '0 3 * * *' # 每日重新生成

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: shivammathur/setup-php@v2
        with: { php-version: '8.2', extensions: mbstring, xml, pdo_mysql }
      - run: composer install --no-dev --optimize-autoloader
      - run: php bin/console app:generate-static-pages
      - uses: peaceiris/actions-gh-pages@v3
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          publish_dir: ./public/static
          destination_dir: .

結語

靜態生成是「以空間換時間」的經典架構模式。現代化重構關鍵點:嚴格型別、依賴注入、原子性寫入、模板引擎解耦、CI/CD 自動化。對於內容導向、讀多寫少、SEO 敏感的頁面 (部落格、文檔、商品詳情、落地頁),靜態生成 + CDN 邊緣分發是成本最低、效能最強、安全性最高的方案。若需即時互動 (評論、個性化推薦),採用 SSG + 客戶端 JS 獲取動態資料 (Islands Architecture / Astro / Next.js 概念) 混合模式。

copyright © 萬盛學電腦網 all rights reserved