动态网站都是从数据库取出数据,分析数据,并输出数据的。网站的瓶颈通常都是反复连接和大量的SQL语句,所以可以对一些经常不变的信息设置缓存。让以后每次请求改页面,都从缓存中读取。
模板引擎分为编译和缓存。编译功能在默认下是开启的。而缓存机制需要开发人员开启。
1、建立缓存。下面是每个模板多个缓存,
<?php
include "libs/Smarty.class.php";
$smarty=new Smarty;
$smarty->setcachedir("./cache");
$smarty->cache_lifetime=60*60*24*7;
/**
$news= $db->getNews($_GET['newid']);
$smarty->assign('newsid',$news->getNewTitle());
$smarty->assign('newdt',$news->getDataTitle());
$smarty->assign('newContent',$news->getNewContent());
*/
$smarty->display('index.tpl',$_SERVER['REQUEST_URL']);
2、display(a,b,c);
a为模板的文件名或者是路径。b指定一个缓存标识符的名称。c在维护一个页面多个缓存时使用。每个页面都有唯一的url。
3、处理开销,其实就是在PHP脚本中动态获取数据和处理操作等的开销。
通过Smarty对象中的isCached();方法 ,判断指定模板的缓存是否存在。
<?php
$smarty->caching=ture;
if($smarty->iscached('index.tpl')){
}
$smarty->display('index.tpl');
4、清除缓存:
$smarty->clearAllCache();
$smarty->clearCache("index.tpl") ;
$smarty->clearCache("index.tpl","CacheID");
代码:
//建立缓存include "libs/Smarty.class.php";$smarty= new Smarty;$smarty->caching=ture;$smarty->setCacheDir("./cache");$smarty->display('index.php');//处理缓存的生命周期include "libs/Smarty.class.php";$smarty= new Smarty;$smarty->caching=ture;$smarty->setCacheDir("./cache");$smarty->cache_lifetime=60*60*24*7;$smarty->display('index.php');//每个模板多个缓存include "libs/Smarty.class.php";$smarty= new Smarty;$smarty->caching=ture;$smarty->setCacheDir("./cache");$smarty->cache_lifetime=60*60*24*7;/* $news=$db->getNews($_GET["newsid"]); $smarty->assign('newsid',$news->getNewTitle()); $smarty->assign('newsdt',$news->getDataTime()); $smarty->assign('newsContent',$news->getNewContent()); */$smarty->display('index.php',$_SERVER['REQUEST_URL']);