針對 PHP 5.1 時代 (約 2006 年) 的 Smarty 手動部署實錄,記錄了從官網下載、解壓、目錄規劃、配置文件封裝、測試驗證到全局共享的完整流程。雖 PHP 版本古老,但其 **「配置集中化、目錄規範化、定界符隔離、全局自動加載」** 的工程化思想仍具參考價值。本文將原文重構為現代視角的標準化部署指南。
/var/www/project/ # 項目根目錄
├── public/ # Web 公開目錄 (DocumentRoot)
│ └── index.php # 入口
├── smarty/ # Smarty 核心庫 (手動部署時放這裡)
│ ├── libs/ # 官方 libs/ 目錄
│ ├── templates/ # 模板源文件
│ ├── templates_c/ # 編譯緩存 (chmod 777)
│ ├── cache/ # 內容緩存 (chmod 777)
│ └── configs/ # 配置文件
├── config.php # Smarty 統一配置入口
└── test.php # 測試腳本
<?php
// config.php - 統一 Smarty 實例工廠
require_once __DIR__ . '/smarty/libs/Smarty.class.php';
/**
* 獲取項目絕對路徑 (兼容 Windows/Linux)
*/
function getProjectRoot(): string {
return rtrim(str_replace('\\', '/', dirname(__DIR__)), '/');
}
$root = getProjectRoot();
$smarty = new Smarty();
$smarty->template_dir = $root . '/smarty/templates/';
$smarty->compile_dir = $root . '/smarty/templates_c/';
$smarty->config_dir = $root . '/smarty/configs/';
$smarty->cache_dir = $root . '/smarty/cache/';
// 定界符隔離 (避免與 JS 框架衝突)
$smarty->left_delimiter = '<{';
$smarty->right_delimiter = '}>';
// 開發環境設置
if (($_SERVER['SERVER_ADDR'] ?? '') === '127.0.0.1' ||
(isset($_SERVER['HTTP_HOST']) && strpos($_SERVER['HTTP_HOST'], 'localhost') !== false)) {
$smarty->force_compile = true;
$smarty->caching = false;
$smarty->debugging = true;
} else {
$smarty->caching = true;
$smarty->cache_lifetime = 3600;
}
// 返回實例供業務腳本使用
return $smarty;
<?php
$smarty = require __DIR__ . '/config.php';
$smarty->assign('title', '測試成功了,這是標題');
$smarty->assign('content', '這是內容');
$smarty->display('test.tpl'); // 對應 smarty/templates/test.tpl
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title><{$title}></title>
</head>
<body>
<{$content}>
</body>
</html>
原文建議修改 php.ini 的 include_path,但**不推薦** (耦合環境、難版本隔離)。現代最佳實踐:
# 各項目 composer.json
{
"require": {
"smarty/smarty": "^4.2"
}
}
# composer install 後自動生成 vendor/autoload.php,互不干擾,版本可獨立升級
/usr/local/share/php/smarty/4.2.1/ # 共享核心庫 (唯讀)
/var/www/projectA/smarty/ # 項目級目錄 (templates/, templates_c/, cache/, configs/)
/var/www/projectB/smarty/
# 項目 config.php
require_once '/usr/local/share/php/smarty/4.2.1/Smarty.class.php';
// ... 設置項目級目錄
優勢:核心庫唯一來源、項目隔離、易於升級回滾、無 php.ini 依賴。
templates_c/、cache/ 目錄存在且 Web 進程用戶 (www-data/php-fpm/IIS_IUSRS) **可讀寫執行**。chown -R www-data:www-data templates_c cache、chmod 775 templates_c cache。<{ }> 或 {% %})。debugging、開啟 caching、設置合理 cache_lifetime。從「解壓 libs 到項目目錄」到「Composer 統一依賴管理」,Smarty 部署方式變了,但 **配置集中化、目錄規範化、環境區分、權限落地** 這四大工程化原則永不過時。本文將 2006 年的手動配置實錄重構為現代標準化指南,助你在維護老項目或理解模板引擎核心機制時少走彎路。