PHP template parsing class instance, PHP template instance
The example in this article describes the PHP template parsing class. Share to everyone for your reference. Specific as follows:
<?phpclass Template {Private $vars = array (), Private $conf = ", private $tpl _name = ' index ';//If the template does not exist, it will find the current control Ler Default Index template private $tpl _suffix = '. html ';//If Config does not have a default suffix, it displays private $tpl _compile_suffix= '. tpl.php ';//compile template path Private $template _tag_left = ' <{';//template Left tag private $template _tag_right = '}> ';//template Right tag private $template _c = ";//Compile Record private $template _path = ";//Template full path private $template _name =";//Template name index.html//The element that defines the label for each template private $tag _foreach = Array (' From ', ' item ', ' key '); Private $tag _include = Array (' file ');//current only supports read template default path public function __construct ($conf) {$this->conf = & $conf; $this->template_c = $this->conf[' template_config ' [' Template_c '];//compile directory $this->_tpl_suffix = $this->tpl _suffix (); } Private Function Str_replace ($search, $replace, $content) {if (empty ($search) | | empty ($replace) | | empty ($content)) re Turn false; Return Str_replace ($search, $replace, $content); }/** * Preg_match_all * @param $pattern Regular * @param $Content contents * @return Array */Private Function Preg_match_all ($pattern, $content) {if (empty ($pattern) | | empty ($conten T)) Core::show_error (' Find template tag failed! '); Preg_match_all ("/". $this->template_tag_left. $pattern. $this->template_tag_right. " /is ", $content, $match); return $match; }/** * Template file suffix */Public Function Tpl_suffix () {$tpl _suffix = empty ($this->conf[' template_config '] [' Template_suffi X '])? $this->tpl_suffix: $this->conf[' template_config ' [' Template_suffix ']; return $TPL _suffix; }/** * not explained here * @return * * * Public Function assign ($key, $value) {$this->vars[$key] = $value;}/** * Render page * @p Aram * Use Method 1 * $this->view->display (' Error ', ' comm/'); * The default is to refer to the TPL template directory, so comm/is tpl/comm/error.html * Use Method 2 * $this->view->display (' ErrorFile '); * Default point to Controller fixed folder * For example, your domain name is http://heartphp/admin/index, then the correct path is tpl/admin/index/errorfile.html * @return */public func tion display ($filename = ', $view _path = ') {$TPL _path_arr = $this->get_tpl ($filename, $view _path);//Gets the TPL full path and transmits the path to the pointer as well as the name if (! $tpl _path_arr) Core::show_error ($ filename. $this->_tpl_suffix. ' Template does not exist '); Compile start $this->view_path_param = $view _path;//user passed the template with the directory $this->compile (); /** * Compile controller * @param * @return * * * Private Function compile () {$filepath = $this->template_path. $this->temp Late_name; $compile _dirpath = $this->check_temp_compile (); $vars _template_c_name = Str_replace ($this->_tpl_suffix, ", $this->template_name); $include _file = $this->template_replace ($this->read_file ($filepath), $compile _dirpath, $vars _template_c_name );//Parse if ($include _file) {$this->read_config () && $config = $this->read_config (); Extract ($this->vars, Extr_skip); [url=home.php?mod=space&uid=48608] @include [/url] $include _file; }}/** * Reads the current project configuration file */protected function Read_config () {if (file_exists (system_path. ' conf/config.php ')) {@include System_path. ' conf/config.php '; return $cOnfig; } return false; }/** * Parse template syntax * @param $str content * @param $compile _dirpath Template Compile directory * @param $vars _template_c_name Template Compile file name * @return compiled PHP template file name */Private Function Template_replace ($str, $compile _dirpath, $vars _template_c_name) {if (empty ($STR)) core::s How_error (' template content is empty! '); Handles the compilation header $compile _path = $compile _dirpath. $vars _template_c_name. $this->tpl_compile_suffix;//Compile file if (Is_file ($ Compile_path) {//$header _content = $this->get_compile_header ($compile _path); $compile _date = $this->get_compile_header_comment ($header _content); $tpl _filemtime = Filemtime ($this->template_path. $this->template_name); $compile _filemtime = filemtime ($compile _path); echo $tpl _filemtime. ' = = '. Date (' y-m-d h:i:s ', $tpl _filemtime). '
'; echo $compile _filemtime. ' = = '. Date (' y-m-d h:i:s ', $compile _filemtime); If the file expires compiling when the template tag has an include and is modified also recompile//<{include file= "public/left.html"}> when modifying the files in the include, non-debug mode if the main file is not changed Currently does not recompile the file in the include, I am considering whether to change, not think well, for the time being, so in the development phase must open debug=1 mode, or modify the include file is invalid. A little wordy, I don't know if it's clear. if ($tpl _filemtime > $compile _filemtime | | DEBUG) {$ret _file = $this->compile_file ($vars _template_c_name, $str, $compile _dirpath); } else {$ret _file = $compile _path; }} else {//compile file does not exist create his $ret _file = $this->compile_file ($vars _template_c_name, $str, $compile _dirpath); } return $ret _file; }/** * Template file Body * @param string $STR content * @return HTML */Private Function body_content ($STR) {//Parse $str = $this-> ;p arse ($STR); $header _comment = "Create on##". Time (). "| Compiled from## ". $this->template_path. $this->template_name; $content = "<? if (!defined (' is_heartphp ')) exit (' Access Denied ');/*{$header _comment}*/?>\r\n$str "; return $content; }/** * Start parsing related template tags * @param $content Template content */Private Function Parse ($content) {//foreach $content = $this->parse_foreach ($content); Include $content = $this->parse_include ($content); If $content = $this->parse_if ($content); ElseIf $content = $this->parse_elseif ($content); Template Label Common part $content = $this->parse_comm ($content); Switch to PHP code $content = $this->parse_php ($content); return $content; }/** * echo if the default direct <{$config [' domain ']}> to <?php echo $config [' domain ']?> */Private Function Parse_echo ($c ontent) {}/** * converted to PHP * @param $content HTML Template content * @return HTML-Replaced HTML */Private Function parse_php ($content) { if (empty ($content)) return false; $content = Preg_replace ("/". $this->template_tag_left. " (.+?)". $this->template_tag_right. " /is "," <?php $?> ", $content); return $content; }/** * If judgment statement * <{if empty ($zhang)}> * Zhang * <{elseif empty ($liang)}> * Liang * <{else}> * Zha Ngliang * <{/if}> * * Private funCtion parse_if ($content) {if (empty ($content)) return false; Preg_match_all ("/". $this->template_tag_left. " If\s+ (. *?) ". $this->template_tag_right. " /is ", $content, $match); $match = $this->preg_match_all ("if\s+ (. *)", $content); if (!isset ($match [1]) | |!is_array ($match [1])) return $content; foreach ($match [1] as $k = + $v) {//$s = Preg_split ("/\s+/is", $v); $s = array_filter ($s); $content = Str_replace ($match [0][$k], "<?php if ({$v}) {?>", $content); } return $content; } Private Function Parse_elseif ($content) {if (empty ($content)) return false; Preg_match_all ("/". $this->template_tag_left. " Elseif\s+ (. *?) ". $this->template_tag_right. " /is ", $content, $match); $match = $this->preg_match_all ("elseif\s+ (. *)", $content); if (!isset ($match [1]) | |!is_array ($match [1])) return $content; foreach ($match [1] as $k = + $v) {//$s = Preg_split ("/\s+/is", $v); $s = array_filter ($s); $content = Str_replace ($match [0][$k], "<?php} elseif ({$v}){?> ", $content); } return $content; }/** * Resolves that the include include tag is not updated in real time when the principal file is updated to update the label content, so want to include the effective please modify the main file * record a time to develop a debug mode when you execute the delete template compilation file * Use method <{include file= "www.phpddt.com"}> * @param $content Template content * @return HTML */Private function Parse_include ($c ontent) {if (empty ($content)) return false; Preg_match_all ("/". $this->template_tag_left. " Include\s+ (. *?) ". $this->template_tag_right. " /is ", $content, $match); $match = $this->preg_match_all ("include\s+ (. *)", $content); if (!isset ($match [1]) | |!is_array ($match [1])) return $content; foreach ($match [1] as $match _key = $match _value) {$a = Preg_split ("/\s+/is", $match _value); $new _tag = Array (); Parse element foreach ($a as $t) {$b = explode (' = ', $t); if (In_array ($b [0], $this->tag_include)) {if (!empty ($b [1])) {$new _tag[$b [0]] = str_replace ("\" "," ", $b [1]); } else {core::show_error (' template path does not exist! '); }}} extract ($new _tag); Query template file foreach ($this->conf[' View_path '] as $v) {$conf _view_tpl = $v. $file;//include template file if (Is_file ($conf _view_tpl)) {$c = $this-> ; Read_file ($conf _view_tpl); $inc _file = Str_replace ($this->_tpl_suffix, ", basename ($file)); $this->view_path_param = dirname ($file). ' /'; $compile _dirpath = $this->check_temp_compile (); $include _file = $this->template_replace ($c, $compile _dirpath, $inc _file);//parsing break; } else {core::show_error (' template file does not exist, please double-check the file: '. $conf _view_tpl); }} $content = Str_replace ($match [0][$match _key], ' <?php include ("'. $include _file. '")? > ', $content); } return $content; }/** * Parsing foreach * Using method <{foreach from= $lists item=value key=kk}> * @param $content Template content * @return HTML parsed content */Private Function Parse_foreach ($content) {if (empty ($content)) return false; Preg_match_all ("/". $this->template_tag_left. " Foreach\s+ (. *?) ". $this->template_tag_right. " /is ", $content, $match); $match = $this->preg_match_all ("forEach\s+ (. *?) ", $content); if (!isset ($match [1]) | |!is_array ($match [1])) return $content; foreach ($match [1] as $match _key = + $value) {$split = Preg_split ("/\s+/is", $value); $split = Array_filter ($split); $new _tag = Array (); foreach ($split as $v) {$a = explode ("=", $v); if (In_array ($a [0], $this->tag_foreach)) {//filter label here does not exist filter $new _tag[$a [0]] = $a [1]; }} $key = '; Extract ($new _tag); $key = ($key)? ' $ '. $key. ' = ': '; $s = ' <?php foreach ('. $from. ' as ' $key. ' $ '. $item. ') {?> '; $content = $this->str_replace ($match [0][$match _key], $s, $content); } return $content; }/** * Match end String */Private Function Parse_comm ($content) {$search = Array ("/". $this->template_tag_left. " \/foreach ". $this->template_tag_right." /is ","/". $this->template_tag_left." \/if ". $this->template_tag_right." /is ","/". $this->template_tag_left." Else ". $this->template_tag_right." /is ",); $replace = Array ("<?php}?>", "<?php }?> "," <?php} else {?> "); $content = Preg_replace ($search, $replace, $content); return $content; }/** * Check the compiled directory if not created recursively create directory * @param string $path file full path * @return Template content */Private Function check_temp_compile () { $paht = $this->template_c. $tpl _path = ($this->view_path_param)? $this->view_path_param: $this->get_tpl_path (); $all _tpl_apth = $this->template_c. $TPL _path; if (!is_dir ($all _tpl_apth)) {$this->create_dir ($tpl _path); } return $all _tpl_apth; }/** * Read file * @param string $path file full path * @return Template content */Private Function Read_file ($path) {//$this->check_file _limits ($path, ' R '); if ($r = @fopen ($path, ' r ') = = = = False) {core::show_error (' template file does not have read or Execute permissions, please check! '); } $content = Fread ($r, FileSize ($path)); Fclose ($R); return $content; }/** * Write file * @param string $filename file name * @param string $content template contents * @return file name */Private Function Compile_fil E ($filename, $content, $dir) {if (empty ($filename)) Core::show_erroR ("{$filename} Creation failed"); $content = $this->body_content ($content),////echo ' Start compiling ===== ' for file contents operation; $f = $dir. $filename. $this->tpl_compile_suffix; $this->check_file_limits ($f, ' w '); if ($fp = @fopen ($f, ' wb ') = = = = False) {Core::show_error ($f. ')
Failed to compile file, please check file permissions. '); }//Open flock flock ($fp, LOCK_EX + lock_nb); Fwrite ($fp, $content, strlen ($content)); Flock ($fp, Lock_un + lock_nb); Fclose ($FP); return $f; }/** * This check file permission function is temporarily deprecated * @param [$path] [path] * @param [status] [W=write, R=read] */Public Function Check_file_limit S ($path, $status = ' rw ') {clearstatcache (); if (!is_writable ($path) && $status = = ' W ') {core::show_error ("{$path}
No write permission, please check. "); ElseIf (!is_readable ($path) && $status = = ' R ') {Core::show_error ("{$path}
No Read permission, please check. "); ElseIf ($status = = ' rw ') {//check wirte and read if (!is_writable ($path) | |!is_readable ($path)) {Core::show_error ("{$ Path
No write or Read permission, please check "); }}}/** * Reads the first row of the compiled template and parses the array * @param string $filepath file path * @param number $line lines * @return Returns the string of the specified number of rows */* Private Function Get_compile_header ($filepath, $line = 0) {if ($file _arr = @file ($filepath)) = = = = False) {Core::show_e Rror ($filepath. '
Failed to read file, please check file permissions! '); } return $file _arr[0]; } *//** * Parse Header Comment Date * @param string $cotnent compile file header first line * @return return Last date */* Private Function Get_compile_header_c Omment ($content) {Preg_match ("/\/\* (. *?) \*\//", $content, $match); if (!isset ($match [1]) | | empty ($match [1])) core::show_error (' Compile error! '); $arr = Explode (' | ', $match [1]); $arr _date = Explode (' # # ', $arr [0]); return $arr _date[1]; } *//** * Gets the full path of the template and returns the existing file * @param string $filename file name * @param string $view _path template path * @return */Private fun Ction Get_tpl ($filename, $view _path) {empty ($filename) && $filename = $this->tpl_name; Traverse the template path foreach ($this->conf[' View_path ') as $path) {if ($view _path) {//Find the file directly from the TPL and directory $tpl _path = $path. $view _path ; $view _file_path = $tpl _path. $filename. $this->_tpl_suffix; } else {//According to the directory, controller, method starts looking for the file $view _file_path = ($tpl _path = $this->get_tpl_path ($path))? $tpl _path. $filename. $this-&G T;_tpl_suffix:exit (0); } if (Is_file ($view _file_path)) {//Transfer the template path and template name to the pointer $this->template_path = $TPL _path;//$this->template_name = $filename. $this->_tpl_suffix; return true; } else {core::show_error ($filename. $this->_tpl_suffix. ' Template does not exist '); }}}/** * Get template path * @param string $path home directory * @return URL D and M stitching path */Private Function Get_tpl_path ($path = ') {C Ore::get_directory_name () && $path _arr[0] = Core::get_directory_name (); Core::get_controller_name () && $path _arr[1] = Core::get_controller_name (); (Is_array ($path _arr))? $newpath = implode ('/', $path _arr): Core::show_error (' Get template path failed! '); Return $path. $newpath. ' /'; /** * Create directory * @param string $path directory * @return */Private Function Create_dir ($path, $mode = 0777) {if (Is_dir ($path )) return false; $dir _arr = explode ('/', $path); $dir _arr = Array_filter ($dir _arr); $allpath = "; $newdir = $this->template_c; foreach ($dir _arr as $dir) {$allpath = $newdir. ' /'. $dir; if (!is_dir ($allpath)) {$newdir = $allpath; if (! @mkdir ($aLlpath, $mode)) {core::show_error ($allpath. ')
Failed to create directory, please check if you have Write permission! '); } chmod ($allpath, $mode); } else {$newdir = $allpath; }} return true; Public Function __destruct () {$this->vars = null; $this->view_path_param = null; }}
I hope this article is helpful to everyone's PHP programming.
http://www.bkjia.com/PHPjc/1029588.html www.bkjia.com true http://www.bkjia.com/PHPjc/1029588.html techarticle PHP Template parsing class instance, PHP template instance This article describes the PHP template parsing class. Share to everyone for your reference. The following: Phpclass template {Private $vars = array (); P ...