【smarty项目源码】模拟smarty模版文件的解析过程

 

[php] view plaincopy
 
  1. <?php  
  2. class MyMiniSmarty{  
  3.     //模版文件的存放路径  
  4.     var $template_dir="./templates/";  
  5.     //编译文件的存放路径 ,编译文件的名称格式暂定为:com_对应的tpl.php  
  6.     var $complie_dir="./templates_c";  
  7.     //模版变量数组:存放所有模版变量的值  
  8.     var $tpl_vars=array();  
  9.   
  10.     //这里我们主要模拟两个方法  
  11.     //参数1-模版变量     参数2:模版变量的值  
  12.     function assign($tpl_var,$val=null){  
  13.           
  14.         if($tpl_var!=''){  
  15.             $this->tpl_vars[$tpl_var]=$var;  
  16.         }  
  17.     }  
  18.   
  19.     //这里编写display  
  20.     //参数1-要显示的模版文件名  
  21.     function display($tpl_file){  
  22.       
  23.         //模版文件的路径  
  24.         $tpl_file_path=$this->template_dir.$tpl_file;  
  25.           
  26.         //编译文件的命名及路径  
  27.         $complie_file_path=$this->complie_dir."com_".$tpl_file.".php";  
  28.   
  29.         //判断当前模版文件是否存在  
  30.         if(!file_exists($tpl_file_path)){  
  31.   
  32.             //如果当前模版文件不存在,则返回false  
  33.             return false;  
  34.   
  35.         }  
  36.   
  37.         //查看是否有编译文件,如果没有编译文件,或者说模版文件的修改时间大于编译文件的生成时间,则需要重新编译  
  38.         if(!file_exists($comlie_file_path) ||filemtime($tpl_file_path)>filemtime($complie_file_path)){  
  39.               
  40.             //获取模版文件的内容  
  41.             $tpl_file_content=file_get_contents($tpl_file_path);  
  42.   
  43.             //这里我们的核心是怎样把tpl转化为php文件  
  44.               
  45.             $pattern=array(  
  46.                 //1.\{ - 转义{ 左括号 2.\s* - 代表一个或多个空格 3.\$ - 转义$符号  4.\} - 转义 } 右括号  
  47.                   
  48.                 '/\{\s*\$([a-zA-Z][a-zA-Z0-9]*)\s*\}/i'  
  49.             );  
  50.   
  51.             $replace=array(  
  52.               
  53.                 '<?php echo $this->tpl_vars["${1}"] ?>'  
  54.             );  
  55.               
  56.             //将类似 {$title}替换为<?php echo $this->tpl_vars["title"] ? >,返回替换后的字符串  
  57.   
  58.             $new_str=preg_replace($pattern,$replace,$tpl_file_content);  
  59.   
  60.             //编译文件的生成:将正则替换后的模版文件中的内容写入到编译文件  
  61.   
  62.             file_put_contents($complie_file_path,$new_str);  
  63.         }  
  64.   
  65.         //如果存在编译文件并且模版文件没有改动,则直接引入编译文件  
  66.         include $complie_file_path;  
  67.     }  
  68. }  
  69. ?>  


注意:对象也可以作为模版变量

 

案例:

php文件:

$smarty=new Smarty();
$var1=“简单字符串”;
$var2=new 对象名();
$var3=array(内容列表..);
$smarty->assign(“var1”,$var1);
$smarty->assign(“var2”,$var2);
$smarty->assign(“var3”,$var3);

 

模版文件:

取出 var1 对应的值:  {$var1}<br/>
取出 var2 对应的值:  {$var2->属性或者方法}
取出 var3 对应的值: {$var3[下标]}

posted @ 2015-11-06 06:39  网络虫  阅读(534)  评论(0编辑  收藏  举报