Smarty除了让php与html代码分离的特性外,还有一个缓存功能,它能够极大提高用户的访问速度,但是一些数据是不能够被缓存的,如用户的状态、网页的统计数据、时间等等,这需要控制好。缓存技术之所以能够提升访问速度,是因为它直接把一个渲染好的html呈现给用户看,无须每次访问都要再查一次数据表,执行一次php代码等等,既减少了数据库的读写、减少服务器负担,也提升用户访问速度。
下面用一个例子说明这个问题。如下图:
有两个时间,一个是执行了Smarty的缓存技术了,一个是禁止缓存的,可以见到每次刷新,执行了Smarty的缓存技术的部分,是读出Smarty在其上次时间间隔缓存出来的页面,一个禁止缓存的部分是再重复执行一次该模板对应php的代码。
首先在Smarty的核心php中设置使用Smarty缓存,同时设置每次缓存的间隔,我这里是Smarty.inc.php,也就是所有用到Smarty特性的php都要引用那个文件:
<?php //首先包含Smarty类文件 include_once('/libs/Smarty.class.php'); //实例化Smarty类文件 $smarty=new Smarty(); $smarty->cache_dir="caches";//缓存文件夹可选为减轻压力 $smarty->caching=true;//关闭缓存,调试中建议关闭,默认为关闭,在实际运行的时候请打开,减轻服务器压力<br /> $smarty->cache_lifetime=10;//缓存存活时间(秒),一般没有这么短的,官方默认为120s $smarty->template_dir="templates";//设置模版目录 $smarty->compile_dir="compiles";//设置编译目录必选 ?>这里将设置每10s缓存一次,实质上这么短是没有什么意义,这里只是为了说明问题。
核心代码是如下这三行:
$smarty->cache_dir="caches";//缓存文件夹可选为减轻压力 $smarty->caching=true;//关闭缓存,调试中建议关闭,默认为关闭,在实际运行的时候请打开,减轻服务器压力<br /> $smarty->cache_lifetime=10;//缓存存活时间(秒),一般没有这么短的,官方默认为120s
cache.php的代码如下,用php代码date("Y-m-d H:i:s")取当前的时间,指派给模板文件cache.html中的{$date}变量。
<?php include "Smarty.inc.php";//使用Smarty特性 function smarty_block_nocache($param,$content,$smarty){return $content;}//部分不缓存 $smarty->registerPlugin("function","nocache", "smarty_block_nocache"); //注册nocache块,之后可以这样用{nocache}不想缓存的内容{/nocache} //Smarty3是用registerPlugin,Smarty2则是用register_block $smarty->assign("date",date("Y-m-d H:i:s")); $smarty->display("cache.html"); ?>
function smarty_block_nocache($param,$content,$smarty){return $content;} $smarty->registerPlugin("function","nocache", "smarty_block_nocache");
而相应的cache.html代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Smarty缓存测试</title> </head> <body> <p>被缓存的部分:{$date}</p> <p>不被缓存的部分:{nocache}{$date}{/nocache}</p> </body> </html>
一般的话,仅即时更新的内容就放到{nocache}标签中即可,其余的话让它缓存去。
参看Smarty为这个cache.html所对应生成的缓存文件,可以发现被缓存的部分是直接写死的,静态内容,而不被缓存部分则是一个待执行的php代码。而实质上用户每次访问页就是这个缓存文件。然而,这对我们程序猿透明,我们只需要自己管好cache.html的即可。