如何用PHP来编写自己的模板引擎

       本文的目的不是为了让大家学会如何编写一个完善的模板引擎,只是为了给PHP初学入门者解释模板引擎的原理和作用。       PHP模板引擎的作用是为了让表现层逻辑和页面本身分开,让程序员和美工的工作可以相对独立,并且减少集成时造成的额外工作量,模板引擎可以做到对Html页面中的变量、流程逻辑等内容用真实内容进行替换、并有缓存功能,减少每次解析的时间,说白了,模板引擎就是利用字符串替换来将模板用数据转换为真正要展示给用户的内容。 1. 原始的编写方法:内容和页面结合在一起。
<?php
        echo “hello world!”;
?>
 
2. 改进的方法:分离
 hello.htm:
<html>
    <body>
        $var
    </body>
</html>

hello.php:       
<?php
$filename="./hello.htm";       
$fp=fopen($filename,'r');
$filecontent=fread($fp,filesize($filename));
fclose($fp);
 
//用变量进行替换
$realcontent=str_replace("\$var","hello world!",$filecontent);
//显示
echo $realcontent;
?> 
       这样,美工就可以针对html文件进行排版编辑,程序员则可以关注与代码实现。
 
3. 一个简单的模板引擎
 模板引擎
<?php
    class templater   
    {		
		var $left_limiter="<\?=";  //变量前界定符
		var $right_limiter="=>";   //变量后界定符 
		var $assign_vars=array();  //存储变量值的数组对象  
		var $searchlevel=2;        //遍历深度
        //将变量赋值给模板引擎
        function assign($varnames, $varvalues)
		{
            $arrvarname=explode(';',$varnames);  //get variable name array
           
            //get variable value array
            if(count($arrvarname)<=1) //can support ";" in value
                $arrvarvalue=array($varvalues);
            else //can not has ";" in variable name or variable value
                $arrvarvalue=explode(';',$varvalues);
           
            //add to intenal variable array       
            for($i=0;$i<count($arrvarname);$i++)
            {                         
                $this->assign_vars[$arrvarname[$i]]=$arrvarvalue[$i];                    
            }
        }
 
		//根据变量名、变量值、模板内容、界定符对内容中的变量用实际值进行替换
		function parsevariable($content, $varname, $varvalue,$left_limiter='',$right_limiter='')
		{
			//get limiter
			if(empty($left_limiter))
				$left_limiter=$this->left_limiter;
			if(empty($right_limiter))
				$right_limiter=$this->right_limiter;
			 
			foreach(array(preg_replace("/['\"]/", "'", $varname), preg_replace("/['\"]/", "\"", $varname)) as $tempvarname)
			{
				$content=preg_replace(  "/".$left_limiter.".*[$]".$tempvarname.".*".$right_limiter."/",
										$varvalue,
										$content);                                                        
			}  
			return $content;           
		}
				 
		//返回替换后的内容
		function get($templatefile)
		{                  
			global $template,$defaulttemplate, $searchlevel;
			//get template file content
			if(file_exists($templatefile))   //if not exist,use default template
				$filecontent=@file_get_contents($templatefile);         
			else
				$filecontent=file_get_contents(str_replace('/'.$template.'/','/'.$defaulttemplate.'/',$templatefile));        
			//replace every variable with value
			for($i=0; $i<$this->searchlevel; $i++)
			{
				foreach ($this->assign_vars as $varname=>$varvalue)             
				{    
					//convert variable with value
					if(strpos($filecontent,$varname))      
					{
						$filecontent=$this->parsevariable($filecontent, $varname, $varvalue);               
					}
				}
			}
			$to = "bak".$templatefile;
			file_put_contents($to,$filecontent);
			return $to;
		}
    }
     
    //实际的用法 
    $objtemplate=new templater; //创建模板引擎对象     
    $objtemplate->assign('var', "hello world!");  //变量赋值 
		
    include $objtemplate->get('hello.htm');    //显示内容
?>	 

模板
hello.htm
<html>
    <body>
        <?= $var =>
    </body>
</html>

4. 需要扩展的功能
 
流程逻辑替换
缓存
性能
 
解决以上问题就可以是一个真正的模板引擎,以后的文章中会介绍如何编写一个功能强大的模板引擎!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值