PHP implements a simple template engine

Source: Internet
Author: User
Tags glob learn php readfile
The template engine is a solution that has been detached from the view layer and model.

First we create a new Template.class.php file.

  '. m ',//Set template file ' Templatedir ' + ' template/',//Set Template folder where ' compiledir ' = ' cache ', ' debug ' = + false,//set to store after compilation The directory ' cache_htm ' = true,//need to be compiled into a static HTML file ' Suffix_cache ' = '. htm ',//compiled file suffix ' cache_time ' =>2000,// How long does automatic Update ' Php_turn ' =>false,//support native PHP code ' cache_control ' = ' control.dat ',);p rivate $compileTool;//Compiler public $filename;//template file name private $value =array ();//value stack static private $instance = Null;public $debug = Array ();//debug Information public funct Ion __construct ($arrayConfig =array ()) {//returns the current UNIX timestamp and subtle number $this->debug[' begin '] = Microtime (true); $this->array Config = $arrayConfig + $this->arrayconfig; $this->getpath (); if (!is_dir ($this->arrayconfig[' Templatedir ']) {exit ("template isnt not Found");} if (!is_dir ($this->arrayconfig[' Compiledir ')) {mkdir ($this->arrayconfig[' Compiledir '],0770,true);} Include ("Compile.class.php");//$this->compiletool = new Compile;} /** path processing is absolute path */public function GetPath () {$this->arrayconfig[' templatedir '] = STRTR (RealpAth ($this->arrayconfig[' Templatedir '), ' \ \ ', '/'). ' /'; $this->arrayconfig[' compiledir ') = Strtr (Realpath ($this->arrayconfig[' Compiledir ']), ' \ \ ', '/'). ' /';} /*** Singleton mode Gets the instance of the template **/public static function getinstance () {if (Is_null (self:: $instance)) {self:: $instance = new Template () ;} Return self:: $instance;} Public Function Setconfig ($key, $value = null) {if (Is_array ($key)) {$this->arrayconfig = $key + $this->arrayconfig;} else{$this->arrayconfig[$key] = $value;}} Public Function getconfig ($key = null) {if ($key) {return $this->arrayconfig[$key];} Else{return $this->arrayconfig;}} /** injects a single variable **/public function assign ($key, $value) {$this->value[$key] = $value;} /** injects multiple variables **/public function Assignarray ($array) {if (Is_array ($array)) {foreach ($array as $k = $v) {$this->value[ $k] = $v;}}} /*** gets the path to the template file **/public function path () {return $this->arrayconfig[' Templatedir '). $this->filename. $this->a rrayconfig[' suffix ');} /*** need to cache **/public function Needcache () {return $this-> arrayconfig[' cache_htm ');} /*** if the cache file needs to be regenerated **/public function recache ($file) {$flag = false;//Generate cache file $cachefile = $this->arrayconfig[' Compiledir '].md5 (@ $filename). '. ' PHP ';//var_dump ($cacheFile); if ($this->arrayconfig[' cache_htm ']===true) {//Set Timeflag (Determine whether the current time-the last time the template file was modified) is less than the set cache time//if less than the return True$timeflag = (Times ()-@filemtime ($cacheFile)) < $this->arrayconfig [' Cache_time ']?true:false;//1, determine if the cache file exists,//2, whether the cache file has content//3, whether the time is within the set cache time if (!is_file ($cacheFile) && FileSize ($cacheFile) >1&& $timeFlag) {$flag = true;} else{$flag = false;}} return $flag;} /*** Display template **/public function Show ($file) {$this->filename = $file; if (!is_file ($this->path ())} {exit (' cannot find the corresponding template ') ;} $compileFile = $this->arrayconfig[' compiledir '). ' /'. MD5 (@ $filename). php '; $cacheFile = $this->arrayconfig[' compiledir '].md5 (@ $filename). HTM ';//echo $compileFile;//echo $cacheFile; if ($this->recache ($file) ===false) {$this->debug[' cached '] = ' False ';//var_dump ($compileFile); $this->compiletool = new ComPile ($this->path (), $compileFile, $this->arrayconfig), if ($this->needcache ()) {//need to cache Ob_start ();} The function imports variables from the array into the current symbol table extract ($this->value,extr_overwrite);//Determines whether the file exists, whether the resulting file is modified less than the template file modification time if (@is_file ($ Compilefile) | | Filemtime ($compileFile)
 
  Path ())) {$this->compiletool->vars = $this->value; $this->compiletool->compile ();//introduction file include $ Compilefile;} Else{include $compileFile;} if ($this->needcache ()) {//If a cache is required $message = ob_get_contents ();//Generate Cache file File_put_contents ($cacheFile, $message) ;}} else{//if the cache file time is less than the set time//Direct read cache file ReadFile ($cacheFile);//$this->debug[' cached '] = true;} $this->debug[' spend '] = Microtime (True)-$this->debug[' begin ']; $this->debug[' count '] = count ($this Value), $this->debug_info (),/*var_dump ($compileFile), Thisvar_dump ($this->path ()), if (!is_file ($compileFile  ) {mkdir ($this->arrayconfig[' Compiledir ')); Here if there is a need to judge $this->compiletool->compile ($this->path (), $compileFile); ReadFile ($compileFile);} Else{readfile ($compileFile);} */}/***debug Debug Functions **/public function Debug_info () {//$this->arrayconfig[' Debug ']=false;if ($this->arrayconfig[ ' Debug ']===true) {var_dump ($this); echo "program run Date", Date ("Y-m-d h:i:s"). "
  
"echo" Template parsing Time ", $this->debug[' spend '], ' s '."
The "; echo" template contains the number of tags, $this->debug[' count ']. "
"; echo" whether to use static cache ", $this->debug[' cached ']."
";//echo" template engine instance parameter ", Var_dump ($this->getconfig ());}} /****** Clear Cached file *****/public function clean ($path = null) {if ($path = null) {$path = $this->arrayconfig[' compiledir '];$ Path = Glob ($path. ' * '. $this->arrayconfig[' Suffix_cache '); the//glob function returns a match to the specified folder directory}else{$path = $this->arrayconfig[' Compiledir '). MD5 ($path). HTM '; foreach ((array) $path as $v) {//delete unlink ($v);}}}

Create a new Compile.class.php translation template file

 template = $template; $this->comfile = $compileFile; $this->content = file_get_contents ($template); if ($config [' Php_turn ']===false) {//echo "123";//$this->t_r[]= "";} echo "123";//Regular match {$xxx} format $this->t_p[]= "#\{\\$ ([a-za-z_\x7f-\xff][a-za-z0-9_\x7f-\xff]*) \}#"; $this->t_r[ ]="
 value[' \\1 '];? > ";} Public function compile () {$this->c_var2 ();//$this->c_staticfile ();//var_dump ($this); File_put_contents ($ This->comfile, $this->content);} Public Function C_var2 () {//replace {$xxx} with
 $this->content = preg_replace ($this->t_p, $this->t_r, $this->content);} Public Function C_staticfile () {$this->content =preg_replace (' #\{\! (. *?) \!\}# ', ', $this->content);} Public Function __set ($name, $value) {$this, $name = $value;} Public Function __get ($name) {return $this, $name;}}

Create a new test file test.php

 
  False, ' debug ' =>false); $tpl->assign (' data ', ' Hello World '); $tpl->show (' member ');//var_dump ($TPL, GetConfig ());

Template file member.m

Welcome

{$data}

Show

Learn PHP core technologies and best practices

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.