PHP中面向對象中的模板引擎類

<?php

/**
* 模版引擎類
*/
class Tpl
{

	//緩存目錄
	protected $cacheDir = './Cache/';
	//模版目錄
	protected $tplDir = './Tpl/';
	//保存變量的成員方法
	protected $vars = [];
	//緩存有效期
	protected $cacheLifeTime = 3600;


	//初始化成員屬性
	public function __construct($tplDir = null ,$cacheDir = null ,$cacheLifeTime = null)
	{
		//判斷緩存目錄是否存在
		if (isset($tplDir)) {
			if ($this->_checkDir($tplDir)) {
				$this->tplDir = rtrim($tplDir,'/') . '/';
			}
		}
		//判斷模板路徑是否存在  若是不存在要建立,權限是否可寫 就須要更改權限
		if (isset($cacheDir)) {
			if ($this->_checkDir($cacheDir)) {
				$this->tplDir = rtrim($cacheDir,'/') . '/';
			}
		}
		//初始化緩存時間
		if (isset($cacheLifeTime)) {
			$thsi->cacheLifeTime = $cacheLifeTime;
		}
	}

	//目錄的建立以及權限的處理
	private function _checkDir($path)
	{
		//判斷是否存在目錄以及是不是目錄
		if (!file_exists($path) || !is_dir($path)) {
			 return mkdir($path,0755,true);
		}

		//判斷目錄的權限是否可讀可寫
		if (!is_readable($path) || !is_writable($path)) {
			return chmod($path,0755);
		}

		return true;
	}

	//分配變量 主要的目的是將模板中須要處理的代碼在php中替換作準備
	public function assign($key,$val)
	{
		$this->vars[$key] = $val;

	}

	//display 顯示模板文件
	public function display($file,$isExecute = true ,$uri = null)
	{

	   	//得到模板路徑(模板目錄路徑+模板文件)
	   	$tplFilePath = $this->tplDir.$file;
		//判斷文件是否存在
		if (!file_exists($tplFilePath)) {
			exit('模板文件不存在');		}
		//得到編譯文件路徑(組合一個全新的文件名和路徑)
		$cacheFile = md5($file.$uri) . '.php';

		$cacheFilePath  = $this->cacheDir . $cacheFile;

		//檢測是否編譯過 是否修改過模板文件 若是變編譯過 並且在有效期內則不編譯
		if (!file_exists($cacheFilePath)) {
			$html = $this->compile($tplFilePath);

		} else {

			//若是修改過模版文件  就須要刪除原來的編譯文件從新編譯
			if (filemtime($tplFilePath) > filemtime($cacheFilePath)) {

				//刪除原來的文件
				unlink($cacheFilePath);

				//從新編譯
				$html = $this->compile($tplFilePath);

			}

			//文件建立時間+緩存有效期 > time() [當前時間], 沒有過時  不然過時
			$isTimeout = (filemtime($tplFilePath) + $this->cacheLifeTime > time()) ? false : true;

			if ($isTimeout) {
				$html = $this->compile($tplFilePath);
			}
		}

		//編譯
		if (isset($html)) {
			if (!file_put_contents($cacheFilePath, $html)) {
				exit('編譯文件寫入失敗');
			}
		}

		//執行
		if ($isExecute) {
			extract($this->vars);
			include $cacheFilePath;
		}
	}

	//編譯的方法  將html的php代碼替換成php代碼來執行 而且生成一個緩存
	protected function compile($tplFilePath)
	{
		//將整個文件讀入一個字符串
		$html = file_get_contents($tplFilePath);

		//正則替換規則
		$keys = [
			'{if %%}' => '<?php if(\1): ?>',
            '{else}' => '<?php else : ?>',
            '{else if %%}' => '<?php elseif(\1) : ?>',
            '{elseif %%}' => '<?php elseif(\1) : ?>',
            '{/if}' => '<?php endif;?>',
            '{$%%}' => '<?=$\1;?>',
            '{foreach %%}' => '<?php foreach(\1) :?>',
            '{/foreach}' => '<?php endforeach;?>',
            '{for %%}' => '<?php for(\1):?>',
            '{/for}' => '<?php endfor;?>',
            '{while %%}' => '<?php while(\1):?>',
            '{/while}' => '<?php endwhile;?>',
            '{continue}' => '<?php continue;?>',
            '{break}' => '<?php break;?>',
            '{$%% = $%%}' => '<?php $\1 = $\2;?>',
            '{$%%++}' => '<?php $\1++;?>',
            '{$%%--}' => '<?php $\1--;?>',
            '{comment}' => '<?php /* ',
            '{/comment}' => ' */ ?>',
            '{/*}' => '<?php /* ',
            '{*/}' => '* ?>',
            '{section}' => '<?php ',
            '{/section}' => '?>',
			'{{%%(%%)}}' => '<?=\1(\2);?>',

			'{include %%}' => '<?php include "\1";?>',

		];

			//經過遍歷 而後一一替換
		foreach ($keys as $key => $value) {
				//正則匹配替換
			$patten = '#' . str_replace('%%', '(.+)', preg_quote($key,'#')) . '#imsU';

			$replace = $value;

			//包含文件處理 include處理方式不同
			if (stripos($patten, 'include')) {
				// 執行一個正則表達式搜索而且使用一個回調進行替換
				$html = preg_replace_callback($patten, array($this,'parseInclude'), $html);

			} else {

				$html = preg_replace($patten, $replace, $html);
			}

		}
		return $html;

	}

	protected function parseInclude($data)
	{

		$file = str_replace(['\'','"'],'',$data[1]);

		$path = $this->parsePath($file);

		$this->display($file,false);

		return '<?php  include "' . $path . '";?>';
	}

	//處理文件名  將漢字符號等統一設置爲32位的加密文件名
	protected function parsePath($file)
	{

		$path = $this->cacheDir . md5($file).'.php';

		return $path;
	}

	//刪除緩存文件(遞歸)
	public function clearCache()
	{
		self::delDir($this->cacheDir);
	}

	//遞歸刪除緩存的文件
	public static function delDir($path)
	{
		$res = opendir($path);

		while($file = readdir($res)){
			if ($file == '.' || $file == '..') {
				continue;
			}

			$newPath = $path.'/'.$file;

			if (is_dir($newPath)) {

				self::delDir($newpath);
			} else {
				unlink($newPath);
			}
		}
	}

}


測試代碼:php

$tpl = new Tpl();
$tpl->assign('hello','world');
$tpl->assign('chensen','你好森林麼麼噠');


$tpl->display('index.html');
相關文章
相關標籤/搜索