设置缓存 {#caching.setting.up}
首先要做的是通过将 $caching 设置为 Smarty::CACHING_LIFETIME_CURRENT 或 Smarty::CACHING_LIFETIME_SAVED 来启用缓存。
<?php
require('Smarty.class.php');
$smarty = new Smarty;
// 使用 $smarty->cacheLifetime() 的值来确定
// 缓存的有效期(秒)
$smarty->setCaching(Smarty::CACHING_LIFETIME_CURRENT);
$smarty->display('index.tpl');
?>
启用缓存后,对 display('index.tpl') 的函数调用将像往常一样渲染模板,但也会将其输出的副本保存到 $cache_dir 中的一个文件(缓存的副本)。在下一次调用 display('index.tpl') 时,将使用缓存的副本,而不是再次渲染模板。
注意
$cache_dir中的文件名与模板名类似。尽管它们以.php扩展名结束,但它们并非旨在直接执行。不要编辑这些文件!
每个缓存页面都有一个由 $cache_lifetime 确定的有限生命周期。默认值是 3600 秒,或一小时。在该时间过后,缓存将被重新生成。通过将 $caching 设置为 Smarty::CACHING_LIFETIME_SAVED,可以为每个缓存设置各自的过期时间。参见 $cache_lifetime 以获取更多详情。
<?php
require('Smarty.class.php');
$smarty = new Smarty;
// 为每个特定的 display 调用保留当前的缓存生命周期
$smarty->setCaching(Smarty::CACHING_LIFETIME_SAVED);
// 将 index.tpl 的 cache_lifetime 设置为 5 分钟
$smarty->setCacheLifetime(300);
$smarty->display('index.tpl');
// 将 home.tpl 的 cache_lifetime 设置为 1 小时
$smarty->setCacheLifetime(3600);
$smarty->display('home.tpl');
// 注意:以下的 $cache_lifetime 设置在 $caching
// 被设置为 Smarty::CACHING_LIFETIME_SAVED 时不会起作用。
// home.tpl 的缓存生命周期已经被设置
// 为1小时,不再遵循 $cache_lifetime 的值。
// home.tpl 的缓存仍然会在1小时后过期。
$smarty->setCacheLifetime(30); // 30 秒
$smarty->display('home.tpl');
?>
如果启用了 $compile_check(默认),则会检查与缓存文件相关的每个模板文件和配置文件是否被修改。如果任何文件自生成缓存以来已被修改,缓存将立即重新生成。这是一个计算开销,因此为了优化性能,将 $compile_check 设置为 FALSE。
<?php
require('Smarty.class.php');
$smarty = new Smarty;
$smarty->setCaching(Smarty::CACHING_LIFETIME_CURRENT);
$smarty->setCompileCheck(false);
$smarty->display('index.tpl');
?>
如果启用了 $force_compile,缓存文件将始终被重新生成。这有效地禁用了缓存,但同时也严重降低了性能。$force_compile 旨在用于 调试 目的。禁用缓存的适当方式是将 $caching 设置为 Smarty::CACHING_OFF。
isCached() 函数可以用来测试一个模板是否有有效的缓存。如果你有一个需要如数据库抓取等操作的缓存模板,你可以使用此函数来跳过该过程。
<?php
require('Smarty.class.php');
$smarty = new Smarty;
$smarty->setCaching(Smarty::CACHING_LIFETIME_CURRENT);
if(!$smarty->isCached('index.tpl')) {
// 没有可用的缓存,此处进行变量分配。
$contents = get_database_contents();
$smarty->assign($contents);
}
$smarty->display('index.tpl');
?>
你可以使用 {nocache}{/nocache} 块函数,{insert} 函数,或者使用大多数模板函数的 nocache 参数,使页面的部分内容保持动态(禁用缓存)。
假设整个页面可以被缓存,除了一个显示在页面侧边的横幅。通过使用 {insert} 函数为横幅,你可以在缓存内容中保持这个元素的动态性。请参见 {insert} 的文档以获取更多详情和示例。
你可以使用 clearAllCache() 函数清除所有缓存文件,或者使用 clearCache() 函数清除单个缓存文件和组。
<?php
require('Smarty.class.php');
$smarty = new Smarty;
$smarty->setCaching(Smarty::CACHING_LIFETIME_CURRENT);
// 只清除 index.tpl 的缓存
$smarty->clearCache('index.tpl');
// 清除所有缓存文件
$smarty->clearAllCache();
$smarty->display('index.tpl');
?>