smarty提供的是文件缓存:将不经常变动且访问量比较大的页面缓存成静态页面(其实是PHP文件)保存在缓存目录下(有过期时间)。
缓存文件其实是PHP文件,并不是静态的html页面,原因如下:
1、页面一旦缓存,所有的内容都是静态的,但实际上,有些内容是不能使用静态的,比如用户状态,时间显示等。(需要使用局部不缓存)
2、缓存文件本身是php文件,因为它要处理局部不缓存的情况。而且过期时间也保存在缓存文件里(静态页面无法处理判断过期时间)。
默认情况下是,smarty是没有开启缓存。
需要设置,开启缓存,有如下几个配置项:
1、开启缓存,caching
2、缓存目录,cache_dir
3、缓存有效期,cache_lifetime,单位是s,默认值3600,一个小时
BaseController.class.php(前台基础控制器):
<?php
//前台基础控制器
class BaseController extends Controller {
//构造方法
public function __construct(){
// 引入smarty类
include APP_PATH . "third_party/smarty/Smarty.class.php";
// 实例化smarty对象
$this->smarty = new Smarty();
// 设置相关属性
$this->smarty->template_dir = CUR_VIEW_PATH . "templates";
$this->smarty->compile_dir = CUR_VIEW_PATH . "templates_c";
//开启缓存
$this->smarty->caching = true;
//设置缓存目录
$this->smarty->cache_dir = CUR_VIEW_PATH . "cache";
//设置有效期
$this->smarty->cache_lifetime = 60;
//开启smarty调试模式,方便观察对比访问网页所需时间。
//$this->smarty->debugging = true; //开启smarty的调试模式,需要\smarty\libs\debug.tpl文件。
if (!$this->smarty->isCached('index.html')) { //判断是否有缓存。如果有缓存就不需要再查数据库了,提高速度
//获取所有的分类
$categoryModel = new CategoryModel('category');
$cats = $categoryModel->frontCats();
$this->smarty->assign('cats',$cats); //将查询数据生成静态文本保存在缓存文件中。
}
$this->smarty->assign('index',false); //用于判断是否是首页的变量。默认不是首页false。
}
}
IndexController.class.php(前台首页控制器):
<?php
//前台首页控制器
class IndexController extends BaseController {
//显示首页
public function indexAction(){
if (!$this->smarty->isCached('index.html')) { //如果有缓存,就不需要再查数据库了。
//获取推荐商品
$goodsModel = new GoodsModel('goods');
$bestGoods = $goodsModel->getBestGoods();
$this->smarty->assign('bestGoods',$bestGoods); //smarty会将该变量生成静态文本保存在缓存文件中。
}
// 载入模板文件
$this->smarty->assign('index',true); //用于判断当前页面是否是首页。true表示是首页
$this->smarty->display('index.html');
}
//清除缓存
public function clearAction(){
//删除首页缓存
// $this->smarty->clearCache('index.html');
//删除指定页面的指定缓存
// $this->smarty->clearCache('goods.html',2);
//删除所有
$this->smarty->clearAllCache();
}
}