寫一個屬於自己的模板引擎【一】

參考文檔《毛毛蟲教你寫一個屬於自己的模板引擎》,自己也模仿着寫一遍,原諒我比較懶,具體詳解請百度原作者作品。

stupid.class.php

<?php 
define('TPL_DIR','./templates/');
define('TPL_C_DIR','./templates_c/');
class Stupid{
	private $_tpl_vars;	//模板變量
	private $_tpl_file;	//模板文件名
	private $_parser;	//編譯對象
	private $_debugger;	//調試對象

	public function Stupid(){
		if( !is_dir(TPL_DIR) || !is_dir(TPL_C_DIR) ){
			exit("錯誤:請正確設置模板文件和編譯文件夾!");
		}
	}

	//assign
	public function assign($var,$value){
		if( isset($var)&&trim($var)!='' ){
			$this->_tpl_vars[$var] = $value;
		}else{
			exit("錯誤:請設置變量名!");
		}
	}

	//display
	public function display($tpl_file){
		$template_file = TPL_DIR.$tpl_file."php";
		if( !file_exists($template_file) ){
			exit("模板文件不存在!");
		}

		$parsed_file = TPL_C_DIR.md5($tpl_file)."php";
		//編譯模板文件
		if( !file_exists($parsed_file) || filemtime($parsed_file)<filemtime($template_file) ){
			require_once './stupid_parser.class.php';
			$this->_parser = new StupidParser();
			$this->_parser->compile($tpl_file);
		}
		include $parsed_file;
	}

	//debug()方法
	public function debug($tpl_file){
		if( include_once("stupid_debugger.class.php") ){
			$this->_debugger = new StupidDebugger($tpl_file);
			$this->_debugger->start();
		}else{
			exit("錯誤:Debugger類不存在");
		}
	}

}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章