首先須要在mySmarty中添加配置信息,開啓緩存,設置緩存文件存放目錄,設置緩存時間
緩存能夠實現減小訪問數據庫,減輕數據庫壓力,訪問一次數據庫,造成靜態頁面,下次直接調用這個頁面,也能夠用nocache標籤實現局部不緩存php
在mysmarty類中添加的語句css
$this->cache_dir='./cache';//緩存文件存放目錄 //開啓緩存 $this->caching=true; //配置緩存的生命週期 $this->cache_lifetime=3600;//單位是秒
控制頁面01.phphtml
<?php //演示緩衝 require('../../smarty3/libs/smarty.class.php'); require('./mySmarty.php'); //定義方法 function insert_welcome(){ return 123; } //建立對象 $smarty=new mySmarty(); //是否開啓緩存 $arr=array(); if(!$smarty->isCached('01.html')){ $conn=mysql_connect('localhost','root','111111'); mysql_query('use boolshop',$conn);//選庫 mysql_query('set names utf8',$conn);//設置編碼 $sql='select goods_id,goods_name,goods_number,shop_price from goods limit 5'; $rs=mysql_query($sql,$conn); while(($row=mysql_fetch_assoc($rs))!==false){ $arr[]=$row; } echo '我走了數據庫'; } //$smarty->clearCache('01.html');//強制清除緩存 $smarty->assign('suiji',rand(),true);//若是第三個參數是true,則這個變量不緩存 $smarty->assign('goods',$arr); $smarty->display('01.html'); ?>
顯示頁面01.htmlmysql
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>顯示數據</title> <style type="text/css"> {literal} p{ font-size:25px; background:green; } {/literal} </style> </head> <body> <p>這裏是一個隨機數{rand()*100 nocache}添加nocache屬性不緩存(局部的)<p> <p>這是用assign傳的值{$suiji}</p> 用foreach遍歷數組<br/> {foreach from=$goods key='key' item='v'} <p> id號:{$v['goods_id']},商品名字:{$v['goods_name']},商品價格{$v['shop_price']},商品儲存量 {$v['goods_number']} </p> {/foreach} <p>{insert name='welcome' nocache}</p> </body> </html>