用户在每次访问PHP应用程序时,都会建立新的数据库连接并重新获取一次数据,在经过操作处理形成html代码响应给用户,如果不想每次都重复出现相同的操作,就可以在一次访问php应用程序时,将动态获取的html代码保存为静态的html页面,形成缓存文件,以后每次请求该页面时,直接读取缓存的数据,而不用每次执行相同的操作。
1、建立缓存:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php
include("./libs/Smarty.class.php");
//创建模板对象 new
$tpl = new Smarty();
$tpl->config_dir = './configs'; //指定缓存文件保存的目录
$tpl->caching=true; //启用文件缓存
$tpl->cache_dir='./cache';
$tpl->cache_lifetime=60*60*24; //处理缓存周期时间
$tpl->left_delimiter = '<{';
$tpl->right_delimiter = '}>';
?>
2、清除缓存文件:
如果启动了模板缓存并指定了缓存时间,则页面在缓存的时间内输出结果不变,用户在应用时需要对网站内容进行管理,经常需要更新缓存,立即看到网站内容更改后的输出结果,缓存的更新过程就是先清除缓存在重新创建一次缓存文件,可以用clear_all_cache()来清除所有缓存clear_cache()来清除单个缓存文件,使用clear_cache()方法不仅清除指定模板的缓存也可以清除多个缓存:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php
include("./libs/Smarty.class.php");
//创建模板对象 new
$tpl = new Smarty();
$tpl->config_dir = './configs'; //指定缓存文件保存的目录
$tpl->caching=true;
$smarty->clear_all_cache(); //清除所有缓存文件
$smarty->clear_cache('index.tpl'); 清除某一个缓存
$smarty->clear_cache('index.tpl','CACHEID'); 清除某一个模板的多个缓存中指定缓存号的一个
$smarty->display('index.tpl');
?>
3、关闭缓存:
有以下三种方式处理关闭缓存:
1.使用{insert}使模板的一部分不被缓存
2.可以使用$smarty->register_function($params,&$smarty)阻止插件从缓存中输出
3.使用$smarty->register_block($params,&$smarty)使整片页面中的某一块不被缓存
<?php
function smarty_block_cacheless($params,$content,&$smarty){
return $content;
}
?>