`
jiagou
  • 浏览: 2532983 次
文章分类
社区版块
存档分类
最新评论

php学习笔记(三十九)smarty缓存特性的使用(包括局部缓存)

 
阅读更多


init.smarty.php

<?php

	define("ROOT", ".");

	//解决问题:Warning: strftime() [function.strftime]:
	date_default_timezone_set("Asia/Shanghai");
	include ROOT."/libs/Smarty.class.php";
	
	$tpl = new Smarty();
	
	//smarty初始化
	$tpl->template_dir=ROOT."/templates/";
	$tpl->compile_dir=ROOT."/templates_c/";
	
	//配置文件位置
	$tpl->config_dir=ROOT."/configs/";
	
	$tpl->caching=0;//缓存文件位置;开发阶段不要开启,运行阶段再开启
	$tpl->cache_dir = ROOT."/cache/"; //设置缓存目录
	$tpl->cache_lifetime=60;
	$tpl->left_delimiter="<!--{";
	$tpl->right_delimiter="}-->";
	?>

mysmarty.php

<?php
/**
 * 
 * 以下所有使用变量都要基于设定的前缀和后缀<!--{}-->
 * smarty的缓存类似于网页静态化(使用smarty缓存非常方便)
 * 1.需要开启缓存
 * 2.指定一下缓存的时间
 * 3.指定缓存文件的保存位置
 * 4.清除缓存
 * 		$tpl->clear_cache["模板","cacheID"]
 * 		$tpl->clear_all_cache();
 * 
 * 
 * 注意:
 * 	1.一个模板只能有一个缓存文件
 * 	2.如果一个模板的多个文章,则需要每个文章进行缓存
 * 		$tpl->display("mysmarty.html",cacheid);
 * 		cacheid最好使用:$_SERVER["REQUEST_URI"]地址栏来进行存储
 * 	3.一定要使用smarty函数isCached来判断是否存在缓存
 * 	4.将用户你好,和发表评论时不进行缓存的设置(局部不缓存)
 * 		将数据写在非缓存之外
 * 	方法一:php注册方式
 * 		$tpl->registerPlugin("block", "nocache", "ncache",FALSE);
 * 		注册块函数
 * 		function ncache($param,$content){
 * 			return $content;
 * 		}
 * 	方法二:写块文件
 * 	//注册块需要修改Smarty的编译文件
 * 	//	1.添加块文件
 * 	//	2.修改smartyCompile文件(700行左右)
 * 	//	if($tag_command=="nocache")
 * 	//		$this->_plugins['block'][$tag_command] = array($plugin_func,null,null,null,false);
 * 	//	else 
 * 	//		$this->_plugins['block'][$tag_command] = array($plugin_func,null,null,null,true);
 */
	//如果文件加载失败require会停止继续解析php;而include则会继续向下执行
	require 'init.smarty.php';
	require 'page.class.php';
		
	//判断是否存在缓存文件
	if(!$tpl->isCached("mysmarty.html",$_SERVER["REQUEST_URI"])){
		$title="这是一个文字标题";
		$mysqli = new mysqli("localhost","root","root","hibernate");
		$result = $mysqli->query("select id,name,price from users");
		$page = new Page($result->num_rows,5);
		$result = $mysqli->query("select id,name,price from users {$page->limit}");
		
		$data=array();
		while ($row=$result->fetch_assoc()){
			$data[]=$row;
		}
		$tpl->assign("title",$title);
		$tpl->assign("secT",$data);
		$tpl->assign("fpage",$page->fpage());
		
		echo date("Y-m-d H:i:s");
	}
	//设置为局部缓存
	$tpl->assign("date",date("Y-m-d H:i:s"));

	$tpl->registerPlugin("block", "nocache", "ncache",FALSE);
	/**
	 * 注册块函数
	 * @param unknown_type $param
	 * @param unknown_type $content
	 */
	function ncache($param,$content){
		return $content;
	}
	
	//模板文件名可以随便定义:比如:mysmarty.tpl只有内容是html就可以了
	//第二个参数,每变化一个值就存一份不同的缓存
	$tpl->display("mysmarty.html",$_SERVER["REQUEST_URI"]);
?>

page.class.php

<?php
	class Page {
		private $total; //数据表中总记录数
		private $listRows; //每页显示行数
		private $limit;
		private $uri;
		private $pageNum; //页数
		private $config=array('header'=>"records", "prev"=>"prev", "next"=>"next", "first"=>"first", "last"=>"last");
		private $listNum=8;
		/*
		 * $total 
		 * $listRows
		 */
		public function __construct($total, $listRows=10, $pa=""){
			$this->total=$total;
			$this->listRows=$listRows;
			$this->uri=$this->getUri($pa);
			$this->page=!empty($_GET["page"]) ? $_GET["page"] : 1;
			$this->pageNum=ceil($this->total/$this->listRows);
			$this->limit=$this->setLimit();
		}

		private function setLimit(){
			return "Limit ".($this->page-1)*$this->listRows.", {$this->listRows}";
		}

		private function getUri($pa){
			$url=$_SERVER["REQUEST_URI"].(strpos($_SERVER["REQUEST_URI"], '?')?'':"?").$pa;
			$parse=parse_url($url);

			if(isset($parse["query"])){
				parse_str($parse['query'],$params);
				unset($params["page"]);
				$url=$parse['path'].'?'.http_build_query($params);
				
			}

			return $url;
		}

		public function __get($args){
			if($args=="limit")
				return $this->limit;
			else
				return null;
		}

		private function start(){
			if($this->total==0)
				return 0;
			else
				return ($this->page-1)*$this->listRows+1;
		}

		private function end(){
			return min($this->page*$this->listRows,$this->total);
		}

		private function first(){
			if($this->page==1)
				@$html.='';
			else
				@$html.="<a href='{$this->uri}&page=1'>{$this->config["first"]}</a>";

			return $html;
		}

		private function prev(){
			if($this->page==1)
				@$html.='';
			else
				@$html.="<a href='{$this->uri}&page=".($this->page-1)."'>{$this->config["prev"]}</a>";

			return $html;
		}

		private function pageList(){
			$linkPage="";
			
			$inum=floor($this->listNum/2);
		
			for($i=$inum; $i>=1; $i--){
				$page=$this->page-$i;

				if($page<1)
					continue;

				$linkPage.="<a href='{$this->uri}&page={$page}'>{$page}</a>";

			}
		
			$linkPage.="{$this->page}";
			

			for($i=1; $i<=$inum; $i++){
				$page=$this->page+$i;
				if($page<=$this->pageNum)
					$linkPage.="<a href='{$this->uri}&page={$page}'>{$page}</a>";
				else
					break;
			}
			return $linkPage;
		}

		private function next(){
			if($this->page==$this->pageNum)
				@$html.='';
			else
				@$html.="<a href='{$this->uri}&page=".($this->page+1)."'>{$this->config["next"]}</a>";
			return $html;
		}

		private function last(){
			if($this->page==$this->pageNum)
				@$html.='';
			else
				@$html.="<a href='{$this->uri}&page=".($this->pageNum)."'>{$this->config["last"]}</a>";
			return $html;
		}

		private function goPage(){
			return '<input type="text" onkeydown="javascript:if(event.keyCode==13){var page=(this.value>'.$this->pageNum.')?'.$this->pageNum.':this.value;location=\''.$this->uri.'&page=\'+page+\'\'}" value="'.$this->page.'" style="width:25px"><input type="button" value="GO" onclick="javascript:var page=(this.previousSibling.value>'.$this->pageNum.')?'.$this->pageNum.':this.previousSibling.value;location=\''.$this->uri.'&page=\'+page+\'\'">';
		}
		function fpage($display=array(0,1,2,3,4,5,6,7,8)){
			$html[0]="total:<b>{$this->total}</b>{$this->config["header"]}";
			$html[1]="pageSize:<b>".($this->end()-$this->start()+1)."</b>,currentSize:<b>{$this->start()}-{$this->end()}</b>";
			$html[2]="<b>{$this->page}/{$this->pageNum}</b>";
			
			$html[3]=$this->first();
			$html[4]=$this->prev();
			$html[5]=$this->pageList();
			$html[6]=$this->next();
			$html[7]=$this->last();
			$html[8]=$this->goPage();
			$fpage='';
			foreach($display as $index){
				$fpage.=$html[$index];
			}
			return $fpage;
		}
	}


mysmarty.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title><!--{$title}--></title>
</head>
<body>
<!--{nocache}-->
<!--{$date}-->
<!--{/nocache}-->
<table	border="1" width="800">
	<tr>
		<th>行号</th>
		<th>索引</th>
		<th>ID</th>
		<th>名称</th>
		<th>价格</th>
	</tr>
	<!--{section loop=$secT name="ls"}-->
	<tr>
		<td><!--{$smarty.section.ls.rownum}--></td>
		<td><!--{$smarty.section.ls.index}--></td>
		<td><!--{$secT[ls].id}--></td>
		<td><!--{$secT[ls].name}--></td>
		<td><!--{$secT[ls].price}--></td>
	</tr>
<!--{sectionelse}-->
	<tr><td>数组为空,或没有分配</td></tr>
<!--{/section}-->
	<tr>
		<td colspan="5"><!--{$fpage}--></td>
	</tr>
</table>
<br>
</body>
</html>



分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics