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

PHP 結合 Smarty 實現靜態頁面生成完整實戰方案

     編輯:PHP 相關知識

靜態化是提升網站效能、降低伺服器負載的經典策略。本文基於 Smarty 模板引擎,展示一套完整的靜態頁面生成方案,涵蓋首頁、列表頁、內容頁的差異化靜態化邏輯,並解決目錄自動建立、模板賦值、檔案寫入等關鍵技術點,適合中小型 CMS 或內容型站點參考。

一、核心思路

  1. 資料準備:從模型層獲取所需資料(文章列表、分類資訊等)。
  2. 模板渲染:呼叫 $smarty->fetch() 將資料填充模板,產生 HTML 字串。
  3. 檔案落地:根據預設路徑規則建立目錄,將 HTML 寫入靜態檔案。
  4. 人工觸發:透過後台按鈕或定時任務主動觸發生成,而非每次請求動態生成,極大降低資料庫壓力。

二、首頁靜態化實作

function staticIndex() {
    global $smarty, $article;

    // 1. 獲取最新 6 條文章
    $newslist = $article->getArticles(null, 54, 'DESC', 1, 6, false, 1, 2, '', 0, 0, 1);

    // 2. 資料預處理:截斷標題、補全字段
    if ($newslist) {
        foreach ($newslist as $k => $v) {
            $newslist[$k]['title_all'] = $v['title'];           // 完整標題
            $newslist[$k]['title'] = cutstr($v['title'], 36, '…'); // 截斷標題
        }
        $smarty->assign('newslist', $newslist);
    }

    // 3. 渲染模板獲取 HTML
    $content = $smarty->fetch('index.html', true);

    // 4. 寫入靜態檔案
    $static_name = ROOT_PATH . 'index.html';
    @file_put_contents($static_name, $content); // 直接覆蓋寫入,無需 fopen

    return true;
}

關鍵點說明:

  • fetch() 第二參數傳 true 表示返回字串而非直接輸出。
  • 使用 file_put_contents() 替代 fopen + fwrite + fclose,程式碼更簡潔且支援原子寫入(配合 LOCK_EX)。
  • 目錄不存在時會自動建立(下文列表頁示例)。

三、列表頁分類靜態化

function staticContent() {
    global $smarty;
    $ids = $this->getListIds(); // 獲取所有需靜態化的內容 ID 列表

    foreach ($ids as $k => $value) {
        // 1. 確保分類目錄存在
        $cat_dir = ROOT_PATH . 'demo/' . $value['catid'] . '/';
        if (!is_dir($cat_dir)) {
            mkdir($cat_dir, 0755, true); // 遞迴建立,權限 0755
        }

        // 2. 獲取單頁渲染內容
        $html_content = $this->getDemoContent($value['demoid']);

        // 3. 定義靜態檔案路徑:demo/分類ID/內容ID.html
        $static_name = $cat_dir . $value['demoid'] . '.html';

        // 4. 寫入檔案
        @file_put_contents($static_name, $html_content);
    }
    return true;
}

// 輔助方法:獲取所有內容 ID
function getListIds() {
    $sql = "SELECT * FROM {$this->tablepre}demo ORDER BY demoid ASC";
    $rs = $this->db->getAll($sql);
    return $rs ?: false;
}

四、內容頁模板渲染邏輯

function getDemoContent($id) {
    global $smarty, $view_templates, $admin_templates;

    loadModel(['demo']);
    $demo = new demo();

    // 1. 設定模板目錄
    $smarty->template_dir = ROOT_PATH . $view_templates;

    // 2. 獲取模板詳情與內容資料
    $getMobanOne = $this->getMobanDetail($id);
    $mobandetail = $demo->MobanList($id);

    // 3. 批量賦值
    foreach ($mobandetail as $k => $v) {
        $smarty->assign($k, $v);
    }

    // 4. 額外賦值
    $this->catid = $getMobanOne['catid'];
    $smarty->assign('pre_title', $mobandetail['membername']);
    $smarty->assign('mobandetail', $mobandetail);

    // 5. 渲染並返回
    $content = $smarty->fetch('demo_show.html', true);
    $smarty->template_dir = ROOT_PATH . $view_templates; // 恢復預設目錄

    return $content;
}

五、方案優化建議

  1. 錯誤處理:為 file_put_contents、mkdir、fetch 加上異常捕獲與日誌記錄。
  2. 併發控制:大量生成時引入鎖機制或佇列(Redis/RabbitMQ),避免同時寫入同一檔案造成損壞。
  3. 增量更新:記錄內容最後修改時間,僅重新生成變更的頁面,而非全量重建。
  4. CDN 同步:生成完成後自動呼叫 CDN 刷新 API(如又拍云、七牛云、阿里云 CDN)。
  5. 模板快取分離:生產環境關閉 Smarty 編譯檢查($smarty->compile_check = false),提升渲染速度。

六、總結

本方案展示了基於 Smarty 的靜態化全流程:資料獲取 → 模板渲染 → 目錄管理 → 檔案落地。核心優勢在於「人工可控、按需生成」,避免了傳統動態頁面的重複查詢與渲染開銷。配合上述優化建議,可構建出高效、穩定、易維護的靜態化系統,支撐日均百萬 PV 級別的內容型站點。

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