正确命令是composer require smarty/smarty:^4.3;Smarty 4.x弃用全局类和libs/目录,须用Composer自动加载并use SmartySmarty,初始化需实例化且配置模板/编译路径。

composer install Smarty 4.x 的正确命令
Smarty 从 4.0 开始不再提供全局 Smarty 类的自动加载入口,直接 require 'libs/Smarty.class.php' 会报错 —— 这是多数人卡住的第一步。
现代用法必须走 Composer 自动加载,且需明确指定版本(因 3.x 和 4.x 不兼容):
- 装最新稳定版(推荐):
composer require smarty/smarty:^4.3 - 若项目强依赖旧版 Smarty 3(如 PHP 5.6 或需
SmartyBC):composer require smarty/smarty:^3.1 - 装完后,
vendor/autoload.php会自动注册命名空间Smarty,不再有Smarty.class.php
在 PHP 中初始化 Smarty 4 实例的最小代码
Smarty 4 弃用了单例和静态方法,所有操作必须通过实例。常见错误是照抄旧文档写 $smarty = new Smarty(); 却没引入类名 —— 它现在在命名空间里。
正确初始化(PHP 7.4+):
require_once __DIR__ . '/vendor/autoload.php';
use SmartySmarty;
$smarty = new Smarty();
$smarty->setTemplateDir(__DIR__ . '/templates/');
$smarty->setCompileDir(__DIR__ . '/var/cache/templates/');
$smarty->display('index.tpl');
- 必须
use SmartySmarty;,否则new Smarty()找不到类 -
setCompileDir()必须可写,否则模板编译失败,报错Unable to write to compile directory - Smarty 4 默认关闭
auto_literal,如果模板里有大量{literal},要手动开:$smarty->setConfig('auto_literal', true)
兼容 Smarty 3 模板语法的注意事项
Smarty 4 默认禁用部分 3.x 语法(如未加引号的字符串参数、{php} 标签),不是“装上就能跑”。
- 启用向后兼容模式(仅限过渡期):
$smarty->setConfig('allow_php_tag', true);和$smarty->setConfig('auto_literal', true) - 模板中避免裸字符串:
{include file=header.tpl}→ 必须写成{include file="header.tpl"} - 插件目录结构变了:旧版插件放
plugins/,新版必须用 PSR-4 命名空间注册,或改用$smarty->addPluginsDir() - 调试时开启
$smarty->setConfig('debugging', true),页面右下角会出现调试窗口,比翻日志快得多
为什么 vendor/smarty/smarty/libs/ 下找不到 Smarty.class.php
这是最常被问“是不是装错了”的点 —— Smarty 4 彻底重构了目录结构,libs/ 目录已移除,核心类都在 src/ 下,且按 PSR-4 规范组织。
- 路径
vendor/smarty/smarty/src/Smarty/Smarty.php对应类SmartySmarty - 如果你在代码里还写
require 'vendor/smarty/smarty/libs/Smarty.class.php',必然失败 - IDE 跳转失效?确认 composer autoload 已生效,并检查
vendor/composer/autoload_psr4.php是否包含"Smarty\" => ["vendor/smarty/smarty/src/"]
旧版模板引擎不是“降级就能用”,而是需要主动适配加载方式和语法边界。最省事的方案,是先锁死 ^3.1,等模板逐步迁移到 4.x 语法再升级。










