
Composer安装Smarty后仍报错因官方包无PSR-4自动加载,Smarty 4+需用new \Smarty\Smarty()并设模板/编译目录,Smarty 3.x须手动require_once加载主类,路径配置错误会导致模板无法加载。
Composer 不能直接“安装 Smarty 模板引擎”——Smarty 不是靠 composer install 就能跑起来的库,它需要手动配置加载逻辑和模板路径,否则会报 Class 'Smarty' not found 或 Unable to load template。
composer require smarty/smarty 后还报错 Class 'Smarty' not found因为官方包 smarty/smarty 只提供源码,不带 PSR-4 自动加载声明;它的类文件用的是传统 require_once 风格加载(如 libs/Smarty.class.php),Composer 默认不会自动包含它。
libs/Smarty.class.php,或自己注册 autoloadersmarty/smarty:^4.0,且命名空间为 Smarty\Smarty,和旧版 Smarty 全局类不兼容smarty-labs/smarty-symfony-bundle)new Smarty() 在 PHP 脚本里真正可用以 Smarty 4.x 为例(推荐,避免魔改):
composer require smarty/smarty:^4.0
然后在入口脚本中:
require __DIR__ . '/vendor/autoload.php';
$smarty = new \Smarty\Smarty();(不是 new Smarty())$smarty->setTemplateDir(__DIR__ . '/templates');、$smarty
->setCompileDir(__DIR__ . '/var/cache/smarty');
Uncaught Error: Class "Smarty\Smarty" not found,检查是否装错了包——运行 composer show smarty/smarty 确认版本 ≥ 4.0.0Smarty 3.x 官方包(smarty/smarty:3.1.*)没有 PSR-4,必须手动加载主类:
composer require smarty/smarty:3.1.49(3.1.49 是最后一个稳定版)require_once __DIR__ . '/vendor/smarty/smarty/libs/Smarty.class.php';
$smarty = new Smarty();
use Smarty; —— 它不是命名空间类;也不要依赖 autoload.files 写死路径,不同环境 vendor 位置可能变化常见错误是 Unable to load template,本质是 Smarty 找不到 .tpl 文件,和 Composer 无关,但容易误判:
$smarty->setTemplateDir() 必须指向含 .tpl 的**目录路径**(不是文件路径),且结尾不带斜杠(Smarty 会自己拼)$smarty->display('index.tpl') 中的 index.tpl 是相对于 template_dir 的相对路径,不是绝对路径compile_dir)和缓存目录(cache_dir)必须存在且 Web 服务器用户有写权限,否则模板无法编译,下次请求仍失败Smarty 的集成难点不在安装命令,而在路径绑定和加载时机——哪怕 composer require 成功了,漏掉 setTemplateDir 或写错 require_once 路径,一样白搭。