⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 lightemplate.class.php

📁 我写的php模版类,调用方法简单,支持if else include之类的标签, 可以包含扩展函数,整个模版文件没有外部include和require,减少io操作, 加载三个模版变量,两个数组变
💻 PHP
字号:
<?php
/**
*    Class name: Lightemplate
*    Run environment on php5.*
*    Project owners and author Troy
*    Code license: GNU General Public License v3
*    Email list:
*        ooofox@msn.com
*    Created on:2009/5/1
*    You need setting an array, when instance this class.
*        $tempConf['templateDir'] setting template files path for template class
*        $tempConf['templateCompiledDir'] save compile file of template
*        $tempConf['templateExtDir'] template extension path
*        $tempConf['templateFileSuffix'] template suffix name, default is .tpl
*    Copyright (c) 2009 Troy
*/
class Lightemplate
{
	static public $tempConf;
	static public $tplFp;
	static public $_arr;
	static public $compileFile;
	static public $extArr;

	public function __construct($tempParams)
	{
		self::$tempConf = $tempParams;
		if(!is_dir(self::$tempConf['templateDir'])){die('template path don\'t exists.');}
		if(!is_dir(self::$tempConf['templateCompiledDir'])){die('template compiled path Don\'t exist.');}
		if(!is_dir(self::$tempConf['templateExtDir'])){die('template extension function path Don\'t exist.');}
		if(!isset(self::$tempConf['templateFileSuffix'])){die('you not set value for suffix of template files.');}
	}


	/**
	*   Access public
	*   Author Troy
	*   Created on 2009/5/2
	*   setting template file
	*/
	public static function setFile($filename)
	{
		self::$compileFile = self::$tempConf['templateCompiledDir'].'/'.$filename.'.php';
		if(file_exists(self::$compileFile)){return true;}
		$tplFile = self::$tempConf['templateDir'].$filename.self::$tempConf['templateFileSuffix'];
		file_exists($tplFile) ? self::$tplFp = file_get_contents($tplFile) : die($tplFile.' don\'t exists');
		$subtpl = self::count_subtemplatefile(self::$tplFp);
		if($subtpl['count']>0)
		{
			foreach($subtpl['subfile'] as $subfile)
			{
				self::$tplFp = preg_replace('~<!-- include '.$subfile.' -->~i',file_exists(self::$tempConf['templateDir'].'/'.$subfile) ? file_get_contents(self::$tempConf['templateDir'].'/'.$subfile) : $subfile.' template file not found!',self::$tplFp);
			}
		}
		self::compile();
		self::fetchIf();
		self::fetchArray();
		return self::$tplFp;
	}


	/**
	*    Access public
	*    Author Troy
	*    Created on:2009/5/2
	*/
	public static function fetchIf()
	{
		if(preg_match_all('~<!-- (else)?if ([0-9a-zA-Z_./]+)[ ]*([!=<>]+)[ ]*(["]?[^"]*["]?) -->~i',self::$tplFp,$arr))
		{
			foreach($arr[2] as $k=>$v)
			{
				$var = self::fetchVar($v);
				$else = ($arr[1][$k] == 'ELSE' or $arr[1][$k] == 'else') ? '} else' : '';
				if(preg_match('/"([^"]*)"/',$arr[4][$k],$foo))
				{
					$code  =  '<?php '.$else.' if ('.$var.' '.$arr[3][$k].' \''.$foo[1].'\'){ ?>';
				}
				elseif (preg_match('/([^"]*)/',$arr[4][$k],$foo))
				{
					$var_other = self::fetchVar($foo[1]);
					$code  =  '<?php '.$else.' if ('.$var_other.' '.$arr[3][$k].' \''.$foo[1].'\'){ ?>';
					//echo $code;exit;
				}
				self::$tplFp = str_replace($arr[0][$k],$code,self::$tplFp);
			}
		}
		if(preg_match_all('~<!-- (ELSE)?IF ([a-zA-Z0-9_.]+) -->~i',self::$tplFp, $arr))
		{
			foreach($arr[2] as $k => $v)
			{
				$else = ($arr[1][$k] == 'ELSE') ? '} else' : '';
				$var = self::fetchVar($v);
				$code = "<?php\n$else"."if (!empty($var)){ ?>";
				self::$tplFp = str_replace($arr[0][$k],$code,self::$tplFp);
			}
		}
		self::$tplFp = preg_replace('~<!-- else -->~i','<?php }else{ ?>',self::$tplFp);
		self::$tplFp = preg_replace("~<!-- endif (.+?) -->~i","<?php }?>",self::$tplFp);
		return self::$tplFp;
	}


	/**
	*    Access Public
	*    Author Troy
	*    Created on:2009/5/3
	*    parse varable of the template
	*/
	public static function fetchVar($var)
	{
		$code = '$_arr';
		if(is_int(strpos($var,'.')))
		{
			$varArr = explode('.',$var);
			for($i=0;$i<count($varArr);$i++)
			{
				$code .= '[\''.$varArr[$i].'\']';
			}
		}
		else
		{
			$code .= '[\''.$var.'\']';
		}
		return $code;
	}


	/**
	*    Access public
	*    Author Troy
	*    Created on:2009/5/2
	*    parse array of the template
	*/
	public static function fetchArray()
	{
		self::$tplFp = preg_replace("~<!-- begin (.+?) -->~i","<?php if(is_array(\$_arr['$1']) && !empty(\$_arr['$1'])){foreach(\$_arr['$1'] as \$rowcnt => $\$1){ \$_arr=&$\$1;?>",self::$tplFp);
		self::$tplFp = preg_replace("~<!-- end (.+?) -->~i","<?php }\$_arr = \$_count[--\$cot];}?>",self::$tplFp);
		return self::$tplFp;
	}


	/**
	*    Access Public
	*    Author Troy
	*    Created on:2009/5/3
	*    compile template file for cache
	*/
	public static function compile()
	{
		preg_match_all("~\{(.+?)\}~",self::$tplFp,$arr);
		for($i=0;$i<count($arr[1]);++$i)
		{
			if(!strpos($arr[1][$i],')'))
			{
				$phpCode = '<?php echo $_arr[\''.str_replace('.','\'][\'',$arr[1][$i]).'\']; ?>';
			}
			else
			{
				$fn=current(explode('(',$arr[1][$i]));
				self::$extArr[].=$fn;
				$phpCode='<?php echo '.$fn.'(';
				preg_match_all("~\((.+?)\)~",$arr[1][$i],$arr1);
				if(strpos($arr1[1][0],','))
				{
					$param = explode(',',$arr1[1][0]);
					for($j=0;$j<count($param);++$j)
					{
						if(is_int(strpos($param[$j],'\'')) or is_int(strpos($param[$j],'"')))
						{
							$param[$j] = preg_replace('~(\'|\")~','',$param[$j]);
							$phpCode .= '\''.str_replace('.','\'][\'',$param[$j]).'\',';
						}
						else
						{
							if(!strpos($param[$j],'.'))
							{
								$phpCode .= '$_arr[\''.$param[$j].'\'],';
							}
							else
							{
								$phpCode .= '$_arr[\''.str_replace('.','\'][\'',$param[$j]).'\'],';
							}
						}
					}
					$phpCode=substr($phpCode,0,-1).');?>';
				}
				else
				{
					if($arr1[1][0]=='')
					{
						$phpCode = '<?php echo '.$fn.'();?>';
					}
					else
					{
						if(is_int(strpos($arr1[1][0],'\'')) or is_int(strpos($arr1[1][0],'"')))
						{
							$arr1[1][0] = preg_replace('~(\'|\")~','',$arr1[1][0]);
							$phpCode .= '\''.str_replace('.','\'][\'',$arr1[1][0]).'\',';
							$phpCode=substr($phpCode,0,-1).');?>';
						}
						else
						{
							$phpCode = '<?php echo '.$fn.'($_arr[\''.str_replace('.','\'][\'',$arr1[1][0]).'\']); ?>';
						}
					}
				}
			}
			self::$tplFp = str_replace($arr[0][$i],$phpCode,self::$tplFp);
		}
	}


	/**
	*   Access public
	*   Author Troy
	*   Created on 2009/5/2
	*   params mixed(string|array) $setName mixed(string|array) $setValue
	*/
	public static function assign($setName,$setValue='')
	{
		if(is_string($setName))
		{
			self::$_arr[$setName] = $setValue;
		}
		if(is_array($setName))
		{
			foreach($setName as $k=>$v)
			{
				self::$_arr[$k] = $v;
			}
		}
		return self::$_arr;
	}


	/**
	*   Access public
	*   Author Troy
	*   Created on 2009/5/2
	*   compile template file
	*/
	private function fetchCompileFile()
	{
		if(!file_exists(self::$compileFile))
		{
			for($i=0;$i<count(self::$extArr);++$i)
			{
				$extFile = self::$tempConf['templateExtDir'].self::$extArr[$i].'.php';
				if(file_exists($extFile))
				{
					$extCon .= php_strip_whitespace($extFile);
				}
				else
				{
					echo $extFile.' not found';
				}
			}
			if(self::$tplFp==''){die('template contents is empty');}
			if(!file_put_contents(self::$compileFile,$extCon.self::$tplFp)){ echo 'make compile file error.';}
		}
		$_arr = &self::$_arr;
		$cot = 0;
		$_count[$cot++] = $_arr;
		include_once(self::$compileFile);
	}


	/**
	*   Access public
	*   Author Troy
	*   Created on 2009/5/2
	*   out put finaly code
	*/
	public static function output()
	{
		self::fetchCompileFile();
	}


	/**
	*    Access public
	*    param $tplCon
	*    count for sub file of templates
	*    Author:Troy
	*    Created on:2009/5/1
	*/
	public static function count_subtemplatefile($tplCon)
	{
		preg_match_all("~<!-- include ([a-zA-Z0-9\-_.\/]+) -->~i",$tplCon,$arr);
		$result['count'] = count($arr[1]);
		$result['subfile'] = $arr[1];
		return $result;
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -