zoukankan      html  css  js  c++  java
  • 模板替换php实战 第三天

    工作之余抽点时间出来写写博文,希望对新接触的朋友有帮助。今天在这里和大家一起学习一下模板替换

        模板和替换

        做了一个新的布局,感觉比以前的舒畅.

        jquery的特效也修改了.移到到内容区块就把文本的颜色改成漂亮的蓝色.移除去掉.

    // JavaScript Document
    $(document).ready(function(e) {
    	$user=$("div .user");
    	$text=$("div .text");
    	
    	$("div .content").each(function(index){
    		$(this).mousemove(function(){
    		
    		$user.eq(index).css("color","#0A8CD2");
    
    	//	$user.eq(index).css("background","#FFE6AD");
    	//	$text.eq(index).css("background","#FFFDF6");
    		
    		}).mouseout(function(){
    		
    		$user.eq(index).css("color","#000");
    
    	//	$user.eq(index).css("background","#E6F0F9");
    	//	$text.eq(index).css("background","#F8FBFD");
    		});
    	});
    
        
    });

        数据库中增加了 time字段,类型为int,长度为 11;

        添加留言时,调用 time()函数返回的ux时间戳,

        数据库中读出时,调用 date()函数

    date('Y-m-d H:i:s',$value['time']);//对时间戳进行转换为日期

        然后还添加了一个分页代码

    function index() {
    
    			include "page.class.php";
     				
    			$rows = $this->db->count('select * from data');
    
    			$page = new Page($rows, 5, "");
    	
    			$page -> set("head", "条留言");
    			$page -> set("first", "首页")
    	   		      -> set("prev", "上一页")
                		      -> set("next", "下一页")
                		      -> set("last", "尾页");	       
    	
    			$list=$this->db
    				   ->order('id DESC')
    			 	   ->limit($page->getLimit())
    			 	   ->select();
    			
    			$this->assign("page",$page->fpage(0,3,4,5,6));
    			$this->assign("list",$list);
    			$this->assign("title", "我的留言板");    //分配标题变量给头部模板header.tpl
    			
    	
    			$this->display();                     //包含替换模板中的变量输出模板页面
    		}

        效果还不错噢.

        page.class.php 源码附上

    <?php
    	/**
    		file: page.class.php 
    		完美分页类 Page 
    		@微凉 QQ496928838
    	*/
    	class Page {
    		private $total;   		 				//数据表中总记录数
    		private $listRows; 						//每页表现行数
    		private $limit;   		 				//SQL语句应用limit从句,制约获得记录个数
    		private $uri;     		 				//主动获得url的请求地址
    		private $pageNum; 		 				//总页数
    		private $page;							//当前页	
    		private $config = array(
    							'head' => "条记录", 
    							'prev' => "上一页", 
    							'next' => "下一页", 
    							'first'=> "首页", 
    							'last' => "末页"
    						); 						//在分页信息中表现内容,可以自己通过set()方法设置
    		private $listNum = 10; 					//默许分页列表表现的个数
    
    		/**
    			构造方法,可以设置分页类的属性
    			@param	int	$total		盘算分页的总记录数
    			@param	int	$listRows	可选的,设置每页须要表现的记录数,默许为25条
    			@param	mixed	$query	可选的,为向目标页面传递参数,可所以数组,也可所以查询字符串格式
    			@param 	bool	$ord	可选的,默许值为true, 页面从第一页开始表现,false则为最后一页
    		 */
    		public function __construct($total, $listRows=25, $query="", $ord=true){
    			$this->total = $total;
    			$this->listRows = $listRows;
    			$this->uri = $this->getUri($query);
    			$this->pageNum = ceil($this->total / $this->listRows);
    			/*以下判断用来设置当前面*/
    			if(!empty($_GET["page"])) {
    				$page = $_GET["page"];
    			}else{
    				if($ord)
    					$page = 1;
    				else
    					$page = $this->pageNum;
    			}
    
    			if($total > 0) {
    				if(preg_match('/\D/', $page) ){
    					$this->page = 1;
    				}else{
    					$this->page = $page;
    				}
    			}else{
    				$this->page = 0;
    			}
    			
    			$this->limit = "LIMIT ".$this->getLimit();
    		}
    
    		/**
    			用于设置表现分页的信息,可以进行联贯操作
    			@param	string	$param	是成员属性数组config的下标
    			@param	string	$value	用于设置config下标对应的元素值
    			@return	object			返回本对象自己$this, 用于连惯操作
    		 */
    		function set($param, $value){
    			if(array_key_exists($param, $this->config)){
    				$this->config[$param] = $value;
    			}
    			return $this;
    		}
    		
    		/* 不是直接去调用,通过该方法,可以应用在对象外部直接获得私有成员属性limit和page的值 */
    		function __get($args){
    			if($args == "limit" || $args == "page")
    				return $this->$args;
    			else
    				return null;
    		}
    		
    		/**
    			按指定的格式输出分页
    			@param	int	0-7的数字分离作为参数,用于自定义输出分页结构和调整结构的顺序,默许输出全体结构
    			@return	string	分页信息内容
    		 */
    		function fpage(){
    			$arr = func_get_args();
    
    			$html[0] = " 共<b> {$this->total} </b>{$this->config["head"]} ";
    			$html[1] = " 本页 <b>".$this->disnum()."</b> 条 ";
    			$html[2] = " 本页从 <b>{$this->start()}-{$this->end()}</b> 条 ";
    			$html[3] = " <b>{$this->page}/{$this->pageNum}</b>页 ";
    			$html[4] = $this->firstprev();
    			$html[5] = $this->pageList();
    			$html[6] = $this->nextlast();
    			$html[7] = $this->goPage();
    
    			$fpage = '<div style="font:12px \'\5B8B\4F53\',san-serif;">';
    			if(count($arr) < 1)
    				$arr = array(0, 1,2,3,4,5,6,7);
    				
    			for($i = 0; $i < count($arr); $i++)
    				$fpage .= $html[$arr[$i]];
    		
    			$fpage .= '</div>';
    			return $fpage;
    		}
    		
    		/* 格式为 1,5,*/
    		function getLimit(){
    			if($this->page > 0)
    				return ($this->page-1)*$this->listRows.", {$this->listRows}";
    			else
    				return 0;
    		}
    
    		/* 在对象内部应用的私有方法,用于主动获得访问的当前URL */
    		private function getUri($query){	
    			$request_uri = $_SERVER["REQUEST_URI"];	
    			$url = strstr($request_uri,'?') ? $request_uri :  $request_uri.'?';
    			
    			if(is_array($query))
    				$url .= http_build_query($query);
    			else if($query != "")
    				$url .= "&".trim($query, "?&");
    		
    			$arr = parse_url($url);
    
    			if(isset($arr["query"])){
    				parse_str($arr["query"], $arrs);
    				unset($arrs["page"]);
    				$url = $arr["path"].'?'.http_build_query($arrs);
    			}
    			
    			if(strstr($url, '?')) {
    				if(substr($url, -1)!='?')
    					$url = $url.'&';
    			}else{
    				$url = $url.'?';
    			}
    			
    			return $url;
    		}
    
    		/* 在对象内部应用的私有方法,用于获得当前页开始的记录数 */
    		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 firstprev(){
    			if($this->page > 1) {
    				$str = " <a href='{$this->uri}page=1'>{$this->config["first"]}</a> ";
    				$str .= "<a href='{$this->uri}page=".($this->page-1)."'>{$this->config["prev"]}</a> ";		
    				return $str;
    			}
    
    		}
    	
    		/* 在对象内部应用的私有方法,用于获得页数列表信息 */
    		private function pageList(){
    			$linkPage = " <b>";
    			
    			$inum = floor($this->listNum/2);
    			/*当前页前面的列表 */
    			for($i = $inum; $i >= 1; $i--){
    				$page = $this->page-$i;
    
    				if($page >= 1)
    					$linkPage .= "<a href='{$this->uri}page={$page}'>{$page}</a> ";
    			}
    			/*当前页的信息 */
    			if($this->pageNum > 1)
    				$linkPage .= "<span style='padding:1px 2px;background:#BBB;color:white'>{$this->page}</span> ";
    			
    			/*当前页前面的列表 */
    			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;
    			}
    			$linkPage .= '</b>';
    			return $linkPage;
    		}
    
    		/* 在对象内部应用的私有方法,获得下一页和尾页的操作信息 */
    		private function nextlast(){
    			if($this->page != $this->pageNum) {
    				$str = " <a href='{$this->uri}page=".($this->page+1)."'>{$this->config["next"]}</a> ";
    				$str .= " <a href='{$this->uri}page=".($this->pageNum)."'>{$this->config["last"]}</a> ";
    				return $str;
    			}
    		}
    
    		/* 在对象内部应用的私有方法,用于表现和处理表单跳转页面 */
    		private function goPage(){
        			if($this->pageNum > 1) {
    				return ' <input style="20px;height:17px !important;height:18px;border:1px solid #CCCCCC;" 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.'"><input style="cursor:pointer;25px;height:18px;border:1px solid #CCCCCC;" type="button" value="GO" onclick="javascript:var page=(this.previousSibling.value>'.$this->pageNum.')?'.$this->pageNum.':this.previousSibling.value;location=\''.$this->uri.'page=\'+page+\'\'"> ';
    			}
    		}
    
    		/* 在对象内部应用的私有方法,用于获得本页表现的记录条数 */
    		private function disnum(){
    			if($this->total > 0){
    				return $this->end()-$this->start()+1;
    			}else{
    				return 0;
    			}
    		}
    	}
        每日一道理
    生活的无奈,有时并不源于自我,别人无心的筑就,那是一种阴差阳错。生活本就是矛盾的,白天与黑夜间的距离,春夏秋冬之间的轮回,于是有了挑剔的喜爱,让无奈加上了喜悦的等待。

        这是一个很强大的分页类噢.虽然模样丑了点,不过,可以改造一下哩

        mysql.class.php呢我修改了一下 limit方法,使他可以支撑一个参数的,和两个参数的,更方便操作了

    public function limit($offset,$length=null){
    		if (is_null($length)) {
    			$this->query_list['limit']='limit '.$offset;
    			return $this;
    		}else {
    			if(!isset($length)){
    				$length = $offset;
    				$offset = 0;
    			}
    				$this->query_list['limit'] = 'limit '.$offset.','.$length;
    				return $this;
    		}

        还学会了设置时区.

    date_default_timezone_set("PRC");    		 //设置时区(中国

        

        修改了 mytpl.class.php 模板引擎,不会形成溢出什么的了

    <?php
        /**
    		file: mytpl.class.php 类名为MyTpl是自定义的模板引擎
    		通过该类对象加载模板文件并解析,将解析后的结果输出 
    		@微凉 QQ496928838
    	*/
    	class MyTpl {
    		public $template_dir = 'view';       //定义模板文件存放的目录  
    		public $compile_dir = 'view_c';      //定义通过模板引擎组合后文件存放目录
    		public $left_delimiter  =  '<{';          //在模板中嵌入动态数据变量的左定界符号
    		public $right_delimiter =  '}>';          //在模板中嵌入动态数据变量的右定界符号
    		private $tpl_vars = array();              //内部应用的临时变量
    		
            /** 
    			将PHP中分配的值会保存到成员属性$tpl_vars中,用于将板中对应的变量进行替换  
    			@param	string	$tpl_var	须要一个字符串参数作为关联数组下标,要和模板中的变量名对应    
    			@param	mixed	$value		须要一个标量类型的值,用来分配给模板中变量的值  	
    		*/
    		function assign($tpl_var, $value = null) {   
    			if ($tpl_var != ''){
    				$GLOBALS[$tpl_var] = $value;
    				$this->tpl_vars[$tpl_var] = $value;
    				
    			}
    
    
    
    		}
    		
            /** 
    			加载指定目录下的模板文件,并将替换后的内容生成组合文件存放到另一个指定目录下
    			@param	string	$fileName	供给模板文件的文件名                                         	
    		*/
             function display($fileName) { 
    			/* 到指定的目录中寻找模板文件 */
    			$tplFile = $this->template_dir.'/'.$fileName;  
    			/* 如果须要处理的模板文件不存在,则退出并呈文错误 */
    			if(!file_exists($tplFile)) {               	
    				die("模板文件{$tplFile}不存在!");
    			}
    			/* 获得组合的模板文件,该文件中的内容都是被替换过的 */
    			$fileNameMd5 = md5($fileName);
    
    			$comFileName = $this->compile_dir."/com_".$fileNameMd5.'.php';  
                		/* 判断替换后的文件是不是存在或是存在但有修改,都须要重新创建 */
    			if(!file_exists($comFileName) || filemtime($comFileName) < filemtime($tplFile)) {
    				/* 调用内部替换模板方法 */
    				$repContent = $this->tpl_replace(file_get_contents($tplFile));  
    				/* 保存由系统组合后的脚本文件 */
    				file_put_contents($comFileName, $repContent);
    			}
    			/* 包含处理后的模板文件输出给客户端 */
    			include($comFileName);		      	
    		}
            
    		/**  
    			内部应用的私有方法,应用正则表达式将模板文件'<{ }>'中的语句替换为对应的值或PHP代码 
    			@param	string	$content	供给从模板文件中读入的全体内容字符串   
    			@return	$repContent			返回替换后的字符串
    		*/
    		private function tpl_replace($content) {
    			/* 将左右定界符号中,有影响正则的特殊符号转义  例如,<{ }>转义\<\{ \}\> */
    			$left = preg_quote($this->left_delimiter, '/');
    			$right = preg_quote($this->right_delimiter, '/');
    
    			/* 匹配模板中各种标识符的正则表达式的模式数组 */
    			$pattern = array(       
    				/* 匹配模板中变量 ,例如,"<{ $var }>"  */
    				'/'.$left.'\s*\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\s*'.$right.'/i', 	
    				/* 匹配模板中if标识符,例如 "<{ if $col == "sex" }> <{ /if }>" */
    				'/'.$left.'\s*if\s*(.+?)\s*'.$right.'(.+?)'.$left.'\s*\/if\s*'.$right.'/ies', 
    				/* 匹配elseif标识符, 例如 "<{ elseif $col == "sex" }>" */
    				'/'.$left.'\s*else\s*if\s*(.+?)\s*'.$right.'/ies', 
    				/* 匹配else标识符, 例如 "<{ else }>" */
    				'/'.$left.'\s*else\s*'.$right.'/is',   
    				/* 用来匹配模板中的loop标识符,用来遍历数组中的值,  例如 "<{ loop $arrs $value }> <{ /loop}>" */
    				'/'.$left.'\s*loop\s+\$(\S+)\s+\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\s*'.$right.'(.+?)'.$left.'\s*\/loop\s*'.$right.'/is',
    				/* 用来遍历数组中的键和值,例如 "<{ loop $arrs $key => $value }> <{ /loop}>"  */
    				'/'.$left.'\s*loop\s+\$(\S+)\s+\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\s*=>\s*\$(\S+)\s*'.$right.'(.+?)'.$left.'\s*\/loop \s*'.$right.'/is', 
    				/* 匹配include标识符, 例如,'<{ include "header.html" }>' */
    				'/'.$left.'\s*include\s+[\"\']?(.+?)[\"\']?\s*'.$right.'/ie'                	
    			);
    			
    			/* 替换从模板中应用正则表达式匹配到的字符串数组 */
    			$replacement = array(  
    				/* 替换模板中的变量 <?php echo $this->tpl_vars["var"]; */
    				'<?php echo $this->tpl_vars["${1}"]; ?>',      
    				/* 替换模板中的if字符串 <?php if($col == "sex") { ?> <?php } ?> */
    				'$this->stripvtags(\'<?php if(${1}) { ?>\',\'${2}<?php } ?>\')', 	
    				/* 替换elseif的字符串 <?php } elseif($col == "sex") { ?> */
    				'$this->stripvtags(\'<?php } elseif(${1}) { ?>\',"")',  
    				/* 替换else的字符串 <?php } else { ?> */
    				'<?php } else { ?>',   
    				/* 以下两条用来替换模板中的loop标识符为foreach格式 */
    				'<?php foreach($this->tpl_vars["${1}"] as $this->tpl_vars["${2}"]) { ?>${3}<?php } ?>',  
    				'<?php foreach($this->tpl_vars["${1}"] as $this->tpl_vars["${2}"] => $this->tpl_vars["${3}"]) { ?>${4}<?php } ?>',    
    				/*替换include的字符串*/
    				'file_get_contents($this->template_dir."/'.$GLOBALS['className'].'/${1}")'
    						
    			);
    			
    			/* 应用正则替换函数处理 */
    			$s_content=$content;
    
    			$repContent = preg_replace($pattern, $replacement, $content); 	
    			/* 如果还有要替换的标识,递归调用自己再次替换 */
    			if(preg_match('/'.$left.'([^('.$right.')]{1,})'.$right.'/', $repContent)) {       
    					if($s_content==$content) {
    						$repContent = $this->tpl_replace($repContent);
    					}
    			} 
    			/* 返回替换后的字符串 */
    
    			return $repContent;                                   	
    		}
    		
             /**
    			内部应用的私有方法,用来将条件语句中应用的变量替换为对应的值
    			@param	string	$expr		供给模板中条件语句的开始标记           
    			@param	string	$statement  供给模板中条件语句的结束标记  
    			@return	strin				将处理后的条件语句相连后返回	
    		*/
    		private function stripvtags($expr, $statement='') {
    			/* 匹配变量的正则 */
    			$var_pattern = '/\s*\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\s*/is'; 
    			/* 将变量替换为值 */
    			$expr = preg_replace($var_pattern, '$this->tpl_vars["${1}"]', $expr); 
    			/* 将开始标记中的引号转义替换 */
    			$expr = str_replace("\\\"", "\"", $expr);
    			/* 替换语句体和结束标记中的引号 */
    			$statement = str_replace("\\\"", "\"", $statement); 
    			/* 将处理后的条件语句相连后返回 */
    			return $expr.$statement;                         	
    		}
    	}

        

    文章结束给大家分享下程序员的一些笑话语录: 问路
    有一个驾驶热气球的人发现他迷路了。他降低了飞行的高度,并认出了地面 上的一个人。他继续下降高度并对着那个人大叫,“打扰一下,你能告诉我我 在哪吗?”
    下面那个人说:“是的。你在热气球里啊,盘旋在 30 英尺的空中”。
    热气球上的人说:“你一定是在 IT 部门做技术工作”。
    “没错”,地面上的人说到,“你是怎么知道的?”
    “呵呵”,热气球上的人说,“你告诉我的每件事在技术上都是对的,但对都没 有用”。
    地面上的人说,“你一定是管理层的人”。
    “没错”,热气球上的人说,“可是你是怎么知道的?”
    “呵呵”,地面上的那人说到,“你不知道你在哪里,你也不知道你要去哪,你 总希望我能帮你。你现在和我们刚见面时还在原来那个地方,但现在却是我 错了”。

  • 相关阅读:
    怎样在UIViewController的生命周期函数中判断是push或者是pop触发的生命周期函数
    配环境
    assert 断言
    mysql:创建新库,新表,查看character
    Python中的[...]是什么?
    同时安装了python3.4和python3.5,如何使用pip?
    亲测可用的优雅的在已经安装了python的Ubuntu上安装python3.5
    如何截网页长图?
    安装tensorflow
    unable to lock the administration directory (/var/lib/dpkg/) is another process using it
  • 原文地址:https://www.cnblogs.com/jiangu66/p/3093395.html
Copyright © 2011-2022 走看看