从此不求人:自主研发一套PHP前端开发框架(24)

正则表达式登场

preg_match_all(‘正则’,’字符串’,匹配结果集)
该函数本身返回boolean,表示匹配成功。
该函数基本用法:
$pattern=’/\w{1,20}/is’;
\w匹配字母、下划线、数字
{1,20} 表示\w的范围在1-20个字符
i是修饰符代表忽略大小写。s修饰符主要针对于.使之包含换行符

解析思路

1.利用正则把{XXX}都取出来
2.把里面的值和$this->_vars 的key进行对比,如存在则替换,否则不予理会
这里有几个正则需要学习
1.代表0个或多个,+代表1个或多个,?代表0个或一个
2.\s代表空格
3.小括号代表分组

_Master.inc

<?php //所有controller的父类 抽象类  abstract class _Master{ var $_view='index';//模板名称 var $_vars = array(); var $_cachetime=0;//缓存时间 function setView($viewName){ $this->_view = $viewName; } function getView(){ return LKPHP_PATH.'/MVC/View/'.LKPHP_VIEWPATH.'/'.$this->_view.'.'.LKPHP_EXTENSION; } function setVar($varName,$varValue){ //设置变量 $this->_vars[$varName] = $varValue; } function hasVarCache(){ if(the_cache($this->_view)){ return true; } return false; } function run(){ //解包变量 if($this->_cachetime > 0){ $getVars_cache = the_cache($this->_view); if($getVars_cache){ echo '<b>这是从memcache中获取的数据</b><br/>'; extract($getVars_cache); }else{ //同时要设置缓存 set_cache($this->_view,$this->_vars,0,$this->_cachetime); extract($this->_vars); } }else{ extract($this->_vars); } extract($this->_vars); if(LKPHP_IS_OPEN_FILE_CACHE){ //这里我们要讲写入缓冲区 $tpl=''; ob_start(); //加载头部模板 include(LKPHP_PATH.'/MVC/View/'.LKPHP_VIEWPATH.'/'.LKPHP_VIEWHEADER.'.'.LKPHP_EXTENSION); include($this->getView());//加载模板body include(LKPHP_PATH.'/MVC/View/'.LKPHP_VIEWPATH.'/'.LKPHP_VIEWFOOTER.'.'.LKPHP_EXTENSION);//尾部 $tpl = ob_get_contents(); ob_clean(); $file_name = md5($_SERVER['REQUEST_URI']); $cache_file='Cache/'.$file_name; if(file_exists($cache_file)){ echo file_get_contents($cache_file); }else{ file_put_contents($cache_file,$tpl); echo $tpl; } }else{ $tpl=''; ob_start(); //加载头部模板 include(LKPHP_PATH.'/MVC/View/'.LKPHP_VIEWPATH.'/'.LKPHP_VIEWHEADER.'.'.LKPHP_EXTENSION); include($this->getView());//加载模板body include(LKPHP_PATH.'/MVC/View/'.LKPHP_VIEWPATH.'/'.LKPHP_VIEWFOOTER.'.'.LKPHP_EXTENSION);//尾部 $tpl = ob_get_contents(); ob_clean(); $tpl=$this->genSimpleVars($tpl); echo $tpl; } } //魔术方法 function __get($p){ $c=load_class($p); return $c; } //解析简单变量 function genSimpleVars($getTpl){ $pattern = "/\{\s*(\w{1,20})\s*\}/is"; if(preg_match_all($pattern,$getTpl,$result)){ $result = $result[1]; foreach ($result as $r) { if(array_key_exists($r, $this->_vars)){ $replace_pattern = "/\{\s*".$r."\s*\}/is"; $getTpl = preg_replace($replace_pattern,$this->_vars[$r],$getTpl); } } } return $getTpl; } } ?>

你可能感兴趣的:(从此不求人:自主研发一套PHP前端开发框架(24))