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 編譯快取無法落地。
<?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_dir | saemc://smartytpl/ | 編譯後模板存放位置,SAE 專用協定 |
| cache_dir | saemc://smartytpl/ | 快取檔案存放位置,可與 compile_dir 共用 |
| compile_locking | false | 關閉檔案鎖,saemc 協定不支援 touch() |
| caching | true | 啟用輸出快取 |
<?php
// 測試頁
$smarty->assign('time', date('Y-m-d H:i:s'));
$smarty->display('index.tpl');
// 第二次重整若顯示相同時間,表示快取生效
?>
force_compile = false,並手動清除 Memcache:Memcache::flush() 或 SAE 控制台重啟服務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 專案。