PHP中面向?qū)ο笾械哪0逡骖?/h1>

<?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,'/') . '/';
			}
		}
		//判斷模板路徑是否存在  如果不存在要創(chuàng)建,權(quán)限是否可寫 就需要更改權(quán)限
		if (isset($cacheDir)) {
			if ($this->_checkDir($cacheDir)) {
				$this->tplDir = rtrim($cacheDir,'/') . '/';
			}
		}
		//初始化緩存時間
		if (isset($cacheLifeTime)) {
			$thsi->cacheLifeTime = $cacheLifeTime;
		}
	}

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

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

		return true;
	}

	//分配變量 主要的目的是將模板中需要處理的代碼在php中替換做準(zhǔn)備
	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;

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

		} else {

			//如果修改過模版文件  就需要刪除原來的編譯文件重新編譯
			if (filemtime($tplFilePath) > filemtime($cacheFilePath)) {

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

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

			}

			//文件創(chuàng)建時間+緩存有效期 > time() [當(dāng)前時間], 沒有過期  否則過期
			$isTimeout = (filemtime($tplFilePath) + $this->cacheLifeTime > time()) ? false : true;

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

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

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

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

		//正則替換規(guī)則
		$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')) {
				// 執(zhí)行一個正則表達(dá)式搜索并且使用一個回調(diào)進(jìn)行替換
				$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 . '";?>';
	}

	//處理文件名  將漢字符號等統(tǒng)一設(shè)置為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);
			}
		}
	}

}

創(chuàng)新互聯(lián)公司專注于汝陽網(wǎng)站建設(shè)服務(wù)及定制,我們擁有豐富的企業(yè)做網(wǎng)站經(jīng)驗(yàn)。 熱誠為您提供汝陽營銷型網(wǎng)站建設(shè),汝陽網(wǎng)站制作、汝陽網(wǎng)頁設(shè)計、汝陽網(wǎng)站官網(wǎng)定制、小程序制作服務(wù),打造汝陽網(wǎng)絡(luò)公司原創(chuàng)品牌,更為您提供汝陽網(wǎng)站排名全網(wǎng)營銷落地服務(wù)。

測試代碼:

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


$tpl->display('index.html');

本文題目:PHP中面向?qū)ο笾械哪0逡骖?/a>
文章轉(zhuǎn)載:
http://muchs.cn/article40/ighoho.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供面包屑導(dǎo)航、域名注冊標(biāo)簽優(yōu)化、品牌網(wǎng)站建設(shè)、營銷型網(wǎng)站建設(shè)、網(wǎng)站營銷

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

手機(jī)網(wǎng)站建設(shè)