萬盛學電腦網

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

SAE 環境下使用 Smarty 模板的 Memcache 設定方案

Sina App Engine (SAE) 因唯讀檔案系統限制,Smarty 預設的檔案快取無法運作。官方解決方案是將 compile_dir 與 cache_dir 指向 Memcache(saemc:// 協定)。本文說明完整設定步驟與注意事項。

問題背景

部署到 SAE 時出現:

SAE_Fatal_error: Uncaught exception 'SmartyException'
with message 'unable to write file ./web/templates_c/wrt4e95555280ef1'

原因:SAE 禁止本地檔案寫入,Smarty 編譯快取無法落地。

解決方案:啟用 Memcache 快取

步驟 1:SAE 控制台開啟 Memcache

  1. 進入 SAE 應用管理 → 服務管理
  2. 啟用 Memcache 服務(初始配額通常免費)
  3. 記下分配的 Memcache 節點資訊(SAE 內部自動解析,無需手動填 IP/Port)

步驟 2:修改 Smarty 設定

<?php
require_once 'Smarty.class.php';

$smarty = new Smarty();

// 【關鍵】指向 SAE Memcache 協定
$smarty->compile_dir = 'saemc://smartytpl/';
$smarty->cache_dir   = 'saemc://smartytpl/';

// 【必要】關閉 compile_locking,避免呼叫 touch() 導致錯誤
$smarty->compile_locking = false;

// 其他建議設定
$smarty->caching = true;           // 啟用快取
$smarty->cache_lifetime = 3600;    // 快取壽命 1 小時
$smarty->force_compile = false;    // 正式環境關閉強制編譯
$smarty->left_delimiter  = '{';
$smarty->right_delimiter = '}';

// 模板目錄(唯讀,放在代碼倉庫中)
$smarty->template_dir = __DIR__ . '/templates/';
?>

關鍵參數說明

參數值說明
compile_dirsaemc://smartytpl/編譯後模板存放位置,SAE 專用協定
cache_dirsaemc://smartytpl/快取檔案存放位置,可與 compile_dir 共用
compile_lockingfalse關閉檔案鎖,saemc 協定不支援 touch()
cachingtrue啟用輸出快取

驗證是否生效

<?php
// 測試頁
$smarty->assign('time', date('Y-m-d H:i:s'));
$smarty->display('index.tpl');

// 第二次重整若顯示相同時間,表示快取生效
?>

常見問題

Q: 模板修改後不生效?
A: 確認 force_compile = false,並手動清除 Memcache:Memcache::flush() 或 SAE 控制台重啟服務
Q: 開發環境如何同步?
A: 本機開發用檔案快取,部署腳本自動切換設定(可用環境變數區分)
Q: 記憶體不足?
A: SAE Memcache 有配額限制,大型專案建議只快取熱門頁面,或升級配額

替代方案:檔案快取掛載到 /tmp

SAE 允許寫入 /tmp 目錄(重啟會清空),可作為臨時編譯目錄:

$smarty->compile_dir = '/tmp/smarty_compile/';
$smarty->cache_dir   = '/tmp/smarty_cache/';
$smarty->compile_locking = true; // 本地檔案可用鎖
⚠️ 僅適合開發/測試環境,正式環境請用 Memcache 確保多實例共享快取。

總結

三行核心設定即可讓 Smarty 在 SAE 正常運行:

$smarty->compile_dir = 'saemc://smartytpl/';
$smarty->cache_dir   = 'saemc://smartytpl/';
$smarty->compile_locking = false;

搭配 SAE 內建 Memcache,零程式碼修改即可無縫遷移既有 Smarty 專案。

copyright © 萬盛學電腦網 all rights reserved