本文是在 thinkphp 模板解析的流程 (http://blog.csdn.net/qq_16877261/article/details/53484671)文章基础上进行讲解的,没看过的同学可以先大致浏览一下。
下面我就直接开始分析,对有必要的源码才会贴出,不必要的就不贴了。
接着上一篇文章讲解 知道 模板解析是该类中的fetch方法开始的,查看代码发现fetch方法调用了loadTemplate,而loadTemplate调用了compiler,compiler调用了parse函数
最后发现解析模板是从该类的parse函数开始的。
下面我重点对这个函数及相关的一些类进行讲解。
public function parse($content) { // 内容为空不解析 if(empty($content)) return ''; //标签库标签开始标记 $begin = $this->config['taglib_begin'];//默认为 < $end = $this->config['taglib_end']; // 默认为 > // 检查include语法 $content = $this->parseInclude($content); // 检查PHP语法 $content = $this->parsePhp($content); // 首先替换literal标签内容 $content = preg_replace_callback('/'.$begin.'literal'.$end.'(.*?)'.$begin.'\/literal'.$end.'/is', array($this, 'parseLiteral'),$content); // 获取需要引入的标签库列表 // 标签库只需要定义一次,允许引入多个一次 // 一般放在文件的最前面 // 格式:<taglib name="html,mytag..." /> // 当TAGLIB_LOAD配置为true时才会进行检测 if(C('TAGLIB_LOAD')) { $this->getIncludeTagLib($content); if(!empty($this->tagLib)) { // 对导入的TagLib进行解析 foreach($this->tagLib as $tagLibName) { $this->parseTagLib($tagLibName,$content); } } } // 预先加载的标签库 无需在每个模板中使用taglib标签加载 但必须使用标签库XML前缀 if(C('TAGLIB_PRE_LOAD')) { $tagLibs = explode(',',C('TAGLIB_PRE_LOAD')); foreach ($tagLibs as $tag){ $this->parseTagLib($tag,$content); } } // 内置标签库 无需使用taglib标签导入就可以使用 并且不需使用标签库XML前缀 $tagLibs = explode(',',C('TAGLIB_BUILD_IN')); foreach ($tagLibs as $tag){ $this->parseTagLib($tag,$content,true); } //解析普通模板标签 {$tagName} $content = preg_replace_callback('/('.$this->config['tmpl_begin'].')([^\d\w\s'.$this->config['tmpl_begin'].$this->config['tmpl_end'].'].+?)('.$this->config['tmpl_end'].')/is', array($this, 'parseTag'),$content); return $content; }
由代码可知需要查看parseInclude 函数
// 解析模板中的include标签 protected function parseInclude($content, $extend = true) { // 解析继承 if($extend) $content = $this->parseExtend($content); // 解析布局 $content = $this->parseLayout($content); // 读取模板中的include标签 $find 匹配的次数 $find = preg_match_all('/'.$this->config['taglib_begin'].'include\s(.+?)\s*?\/'.$this->config['taglib_end'].'/is',$content,$matches); if($find) { for($i=0;$i<$find;$i++) { $include = $matches[1][$i]; $array = $this->parseXmlAttrs($include); $file = $array['file']; unset($array['file']); $content = str_replace($matches[0][$i],$this->parseIncludeItem($file,$array,$extend),$content); } } return $content; }
由于我暂时模板中用不到继承和布局,所以暂时略过下面这两行代码,有兴趣的同学可以研究哈。
if($extend) $content = $this->parseExtend($content); // 解析布局 $content = $this->parseLayout($content);
由代码知道根据正则表达式匹配出 include标签 ,默认的include标签为 <include file="./Public/nav.html"/> 的形式, 而函数preg_match_all (对该函数不了解的需要查看一
下函数)返回的是匹配的次数,所以 $matches[1][$i] 匹配的是第i个include标签的 file="./Public/nav.html" (file里面的内容是可变的,只是举个例子)$matches[0][$i] 匹配的是第i个include标签的 <include file="./Public/nav.html"/>。
parseXmlAttrs 函数的作用是 将匹配到的 file="./Public/nav.html" 放入到xml标签里,然后再进行解析xml属性,返回解析的数组(可看源码)。{这个思想很有用啊,以后有可能会用啊}。
parseIncludeItem 函数解析模板文件并读取模板文件内容,然后再调用parseInclude 进行include 标签解析,一直到没有include标签。采用的是递归的思想。
于是parseInclude 函数的作用:解析include 标签里的文件名,从而读取文件内容,代替当前的include标签。
我接着看parse函数,parsePhp 检查PHP语法, 接着用正则替换掉literal标签内容,并将其放在全局变量$literal中,最后再替换回来,接着代码涉及到标签库。
// 内置标签库 无需使用taglib标签导入就可以使用 并且不需使用标签库XML前缀 $tagLibs = explode(',',C('TAGLIB_BUILD_IN')); foreach ($tagLibs as $tag){ $this->parseTagLib($tag,$content,true); }
Thinkphp 中有许多内置的标签如 <foreach name= 'arr' item='foo'> volist empty 等等,当然也可以自己定义标签库,这么艰巨的任务有兴趣的同学可以尝试一下哈。由于我没有自定义标签库,所以直接看内置标签库的解析就OK了。系统内置的标签库名为“Cx”。
下面我们对 parseTagLib 函数进行解析
/** * TagLib库解析 * @access public * @param string $tagLib 要解析的标签库 * @param string $content 要解析的模板内容 * @param boolean $hide 是否隐藏标签库前缀 * @return string */ public function parseTagLib($tagLib,&$content,$hide=false) { $begin = $this->config['taglib_begin']; $end = $this->config['taglib_end']; if(strpos($tagLib,'\\')){ // 支持指定标签库的命名空间 $className = $tagLib; $tagLib = substr($tagLib,strrpos($tagLib,'\\')+1); }else{ $className = 'Think\\Template\TagLib\\'.ucwords($tagLib); } //实例化标签库 $tLib = \Think\Think::instance($className); $that = $this; //$tLib->getTags() 得到所有标签 foreach ($tLib->getTags() as $name=>$val){ $tags = array($name); if(isset($val['alias'])) {// 别名设置 $tags = explode(',',$val['alias']); $tags[] = $name; } $level = isset($val['level'])?$val['level']:1; $closeTag = isset($val['close'])?$val['close']:true; foreach ($tags as $tag){ //$hide=false 默认标签库$tagLib=Cx $parseTag = !$hide? $tagLib.':'.$tag: $tag;// 实际要解析的标签名称 if(!method_exists($tLib,'_'.$tag)) { // 别名可以无需定义解析方法 $tag = $name; } $n1 = empty($val['attr'])?'(\s*?)':'\s([^'.$end.']*)'; $this->tempVar = array($tagLib, $tag); //我们以 volist 标签为例 $closeTag=true if (!$closeTag){ $patterns = '/'.$begin.$parseTag.$n1.'\/(\s*?)'.$end.'/is'; $content = preg_replace_callback($patterns, function($matches) use($tLib,$tag,$that){ return $that->parseXmlTag($tLib,$tag,$matches[1],$matches[2]); },$content); }else{ // 匹配形式如 <volist name="arr" id="foo"> **</volist> $patterns = '/'.$begin.$parseTag.$n1.$end.'(.*?)'.$begin.'\/'.$parseTag.'(\s*?)'.$end.'/is'; for($i=0;$i<$level;$i++) { //进行标签解析,并将之前的标签替换成解析后的内容 $content=preg_replace_callback($patterns,function($matches) use($tLib,$tag,$that){ return $that->parseXmlTag($tLib,$tag,$matches[1],$matches[2]); },$content); } } } } }
因此又需要查看函数parseXmlTag
/** * 解析标签库的标签 * 需要调用对应的标签库文件解析类 * @access public * @param object $tagLib 标签库对象实例 * @param string $tag 标签名 * @param string $attr 标签属性 * @param string $content 标签内容 * @return string|false */ public function parseXmlTag($tagLib,$tag,$attr,$content) { if(ini_get('magic_quotes_sybase')) $attr = str_replace('\"','\'',$attr); $parse = '_'.$tag; $content = trim($content); // 返回该标签的属性数组 $tags $tags = $tagLib->parseXmlAttr($attr,$tag); return $tagLib->$parse($tags,$content); }
我们仍以标签volist为例,可知该函数又调用了 Cx->_volist 方法。
/** * volist标签解析 循环输出数据集 * 格式: * <volist name="userList" id="user" empty="" > * {user.username} * {user.email} * </volist> * @access public * @param array $tag 标签属性 * @param string $content 标签内容 * @return string|void */ public function _volist($tag,$content) { $name = $tag['name']; $id = $tag['id']; $empty = isset($tag['empty'])?$tag['empty']:''; $key = !empty($tag['key'])?$tag['key']:'i'; $mod = isset($tag['mod'])?$tag['mod']:'2'; // 允许使用函数设定数据集 <volist name=":fun('arg')" id="vo">{$vo.name}</volist> $parseStr = '<?php '; if(0===strpos($name,':')) { $parseStr .= '$_result='.substr($name,1).';'; $name = '$_result'; }else{ //自动识别构建变量 $name = $this->autoBuildVar($name); } //下面这段代码采用了PHP流程控制的替代语法 //左花括号({)换成冒号(:),把右花括号(})分别换成 endif;,endwhile;,endfor;,endforeach; 以及 endswitch; $parseStr .= 'if(is_array('.$name.')): $'.$key.' = 0;'; if(isset($tag['length']) && '' !=$tag['length'] ) { $parseStr .= ' $__LIST__ = array_slice('.$name.','.$tag['offset'].','.$tag['length'].',true);'; }elseif(isset($tag['offset']) && '' !=$tag['offset']){ $parseStr .= ' $__LIST__ = array_slice('.$name.','.$tag['offset'].',null,true);'; }else{ $parseStr .= ' $__LIST__ = '.$name.';'; } $parseStr .= 'if( count($__LIST__)==0 ) : echo "'.$empty.'" ;'; $parseStr .= 'else: '; $parseStr .= 'foreach($__LIST__ as $key=>$'.$id.'): '; $parseStr .= '$mod = ($'.$key.' % '.$mod.' );'; $parseStr .= '++$'.$key.';?>'; $parseStr .= $this->tpl->parse($content); $parseStr .= '<?php endforeach; endif; else: echo "'.$empty.'" ;endif; ?>'; if(!empty($parseStr)) { return $parseStr; } return ; }
至此,完成了标签库的解析,其他标签原理相同。其实就是将所谓的标签正则匹配出来然后用PHP 语句替换。然后我们再一次梳理一下标签解析的步骤:
1、调用parseTagLib函数,实例化标签库,然后获取所有标签,进行遍历,然后对于每个标签调用parseXmlTag函数,并用现有的标签替换标签解析后的内容。
2、根据具体的标签调用具体的标签库里的函数,并返回解析后的PHP代码。
下面我们再一次回到parse函数,请同学们自行查看代码,这里不再贴代码了,标签库解析完之后
$content = preg_replace_callback('/('.$this->config['tmpl_begin'].')([^\d\w\s'.$this->config['tmpl_begin'].$this->config['tmpl_end'].'].+?)('.$this->config['tmpl_end'].')/is', array($this, 'parseTag'),$content);
这一步其实就是替换模板变量。这里不再赘述。有兴趣的同学,可以自行查看。至此,parse函数完成。我们又回到上一个函数compiler函数
其中该函数有一句
Hook::listen('template_filter',$tmplContent);
显然又调用了行为扩展。于是我又去如图目录下找到common.php 文件查看
发现该标签对应的行为扩展类为ContentReplaceBehavior,打开代码查看如下
'template_filter'=> array( 'Behavior\ContentReplaceBehavior', // 模板输出替换 ),
/** * 模板内容替换 * @access protected * @param string $content 模板内容 * @return string */ protected function templateContentReplace($content) { // 系统默认的特殊变量替换 $replace = array( '__ROOT__' => __ROOT__, // 当前网站地址 '__APP__' => __APP__, // 当前应用地址 '__MODULE__' => __MODULE__, '__ACTION__' => __ACTION__, // 当前操作地址 '__SELF__' => htmlentities(__SELF__), // 当前页面地址 '__CONTROLLER__'=> __CONTROLLER__, '__URL__' => __CONTROLLER__, '__PUBLIC__' => __ROOT__.'/Public',// 站点公共目录 ); // 允许用户自定义模板的字符串替换 if(is_array(C('TMPL_PARSE_STRING')) ) $replace = array_merge($replace,C('TMPL_PARSE_STRING')); $content = str_replace(array_keys($replace),array_values($replace),$content); return $content; }
于是发现之前在模板中使用的模板特殊变量原来是在这实现的。至此compiler函数结束了。于是又回到了loadTemplate函数,函数中有这段代码,就是将解析编译后的代码写入缓存文件。并返回缓存文件。
$tmplContent = $this->compiler($tmplContent); Storage::put($tmplCacheFile,trim($tmplContent),'tpl'); return $tmplCacheFile;
于是又回到fetch函数
public function fetch($templateFile,$templateVar,$prefix='') { $this->tVar = $templateVar; $templateCacheFile = $this->loadTemplate($templateFile,$prefix); Storage::load($templateCacheFile,$this->tVar,null,'tpl'); }
其实就是加载缓存文件。至此,整个模板解析、编译,加载过程完成。
如果讲解有不对的地方,欢迎指正