单模板多缓存:缓存商品详情页,但针对不同的商品需要缓存不同的商品详情页。
在display的时候,增加一个参数,唯一标识这个商品。
然后在判断的时候,isCahced中也可以增加一个参数,指定是哪个商品的缓存是否有效。
GoodsController.class.php(商品控制器):
<?php
//前台商品控制器
class GoodsController extends BaseController{
public function indexAction(){
$goods_id = $_GET['goods_id'] + 0;
if (!$this->smarty->isCached('goods.html',$goods_id)) { //通过加入参数 $goods_id 来判断指定的商品页是否已缓存且有效。
$goodsModel = new GoodsModel('goods');
$goods = $goodsModel->selectByPk($goods_id);
// 分配数据
$this->smarty->assign('goods',$goods);
}
// 载入模板文件
$this->smarty->display('goods.html',$goods_id); //通过加入参数 $goods_id 来唯一标识该商品缓存页面
}
}
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。
}
}