自定義簡單的PHP模版引擎

定義文件:php

    1. 建立目錄文件tplhtml

    2. 建立模版處理文件tpl/Template.php學習

    3. 顯示處理頁面 tpl/index.phpui

    4. 建立模版文件 tpl/index.htmlthis

    5. 編譯目錄文件 tpl/compilehtm

 自定義模版引擎目錄結構

tpl/Template.php源代碼blog

<?php
class Template {

	// 模版中的變量
	protected $tplVals = array();

	// 編譯文件路徑
	protected $compileFile = './compile/';

	// 編譯文件擴展名
	private $compileExtendName = '.php';

	// 模版文件擴展名
	private $tplExtendName = '.html';

	public function __construct(){}

	/**
	 * 替換模版文件中的變量
	 * @param  array $data 模版文件的內容
	 * @return  string $data 替換模版文件的內容
	 */
	private function replaceTplVar($data){
		foreach($this->tplVals as $k=>$v) {
			$data = str_replace('{$'.$k.'}', $v, $data);
		}
		return $data;
	}

	/**
	 * 顯示模版
	 * @param  unkown $tpl
	 */
	public function display($tpl) {
		// 獲取模版內容
		$content = file_get_contents($tpl.$this->tplExtendName);
		
		// 替換模版中的變量
		$content = $this->replaceTplVar($content);


		// 編譯後的文件
		$compileFile = $this->compileFile.md5($tpl).$this->compileExtendName;
		
		// 給編譯後的文件添加內容
		file_put_contents($compileFile, $content);
		
		// 引入編譯文件
		require_once $compileFile;
		
	}


	/**
	 * 模版變量綁定
	 * @param  string $name  模版變量名
	 * @param  string $value 模版變量值
	 * @return null
	 */
	public function assign($name, $value) {
		$this->tplVals[$name] = $value;
	}
}

  

tpl/index.php源代碼md5

<?php
require_once './template.php';

$tpl = new Template();
$tpl->assign('title','自定義smart有模版引擎');
$tpl->assign('content','這是模本內容');
$tpl->display('index');

 

 tpl/index.html源代碼utf-8

<!doctype html>
<html>
<head>
<title>歡迎你們來零壹碼學習自定義模版引擎</title>
<meta charset="utf-8" />	
</head>
<body>
	<h1>{$title}</h1>
	<p>{$content}</p>
</body>
</html>

  

執行index.php文件以後結果:get

相關文章
相關標籤/搜索