天天看點

PHP Smarty 檔案緩存(将頁面緩存為靜态頁面)

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();
	}
}