PHP template parsing class instance _php tips

Source: Internet
Author: User

This example describes the PHP template parsing class. Share to everyone for your reference. as follows:

<?php class Template {Private $vars = array ();
 Private $conf = ';
 Private $TPL _name = ' index '; If the template does not exist, it finds the current Controller default index template private $tpl _suffix = '. html ';//If Config does not configure a default suffix, it displays private $tpl _compile_suffix= '. T pl.php '//compile template path private $template _tag_left = ' <{';//template left label private $template _tag_right = '}> ';//template right label private $te 
 Mplate_c = ';//compile directory private $template _path = '//template full path private $template _name = '//template name index.html//define the elements of each template's label
 Private $tag _foreach = Array (' From ', ' item ', ' key ');
  Private $tag _include = Array (' file ');//Currently only supports reading 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))
  return false;
 Return Str_replace ($search, $replace, $content); }/** * Preg_match_all * @pAram $pattern Regular * @param $content content * @return Array */Private Function Preg_match_all ($pattern, $content) {if
  (Empty ($pattern) | | empty ($content)) Core::show_error (' Find template tags 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_ 
       Suffix '])?
  $this->tpl_suffix: $this->conf[' template_config ' [' Template_suffix '];
 return $TPL _suffix;
 /** * Here does not explain * @return/Public Function assign ($key, $value) {$this->vars[$key] = $value;
  /** * Render Page * @param * Use Method 1 * $this->view->display (' Error ', ' comm/'); 
  * The default is to point to the TPL template's directory, so comm/is tpl/comm/error.html * Use Method 2 * $this->view->display (' ErrorFile '); * Default point to the 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 function display ($filename = ', $view _path = ') {$tpl _path_arr = $this->get_tpl ($filename, $view _path);//Get TPL complete Road
  Path and route to the pointer and 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 pass over the template and directory $this->compile (); /** * Compile controller * @param * @return/Private Function compile () {$filepath = $this->template_path. $this-&
  Gt;template_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 Profile/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 compiled directory * @param $vars _template_c_name Templates compile file name * @retu  RN compiled PHP template filename * * Private function Template_replace ($str, $compile _dirpath, $vars _template_c_name) {if (empty ($STR)) Core::show_error (' template content is empty!
  '); Process 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). '
   <br/> '; echo $compile _filemtime. '
   = = '. Date (' y-m-d h:i:s ', $compile _filemtime); If the file is out-of-date compilation is also recompiled when the template label has include and is modified
   <{include file= "public/left.html"}> when modifying files in include, non-debug mode without changing the main file is not currently recompiling include files, I am thinking about whether to change, not think well, This is the case, so be sure to open the Debug=1 mode in the development phase or else modify the include file is invalid. A little wordy, do not know the statement clearly no if ($tpl _filemtime > $compile _filemtime | |
   DEBUG) {$ret _file = $this->compile_file ($vars _template_c_name, $str, $compile _dirpath);
   else {$ret _file = $compile _path;
  } else {//compilation file does not exist create him $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->parse ($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 default direct <{$config [' domain ']}> to <?php echo $config [' domain ']?>/private function Parse_ech O ($content) {}/** * Convert to PHP * @param $content HTML Template content * @return HTML replace good 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}> * Zhangliang * <{/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;
  /** * Parsing the include include tag is not a real-time update when the main file is updated to update the label content, so want to include the effective please modify the main file * record the time to develop a when the debug mode of each execution of the delete template compiled files * Use method <{include file= "www.phpddt.com"}> * @param $content Template content * @return HTML/Private function parse_in
  Clude ($content) {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 ();
    Analysis 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);
    } else {core::show_error (' template file does not exist, please check the file carefully: '. $conf _view_tpl); } $content = Str_replace ($match [0][$match _key], ' <?php include ('. $include _file. ')?
  > ', $content);
 return $content; /** * Parse foreach * use method <{foreach from= $lists item=value key=kk}> * @param $content Template content * @return HTML solution
  The content of the analysis * * 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 does not exist filter $new _tag[$a [0]] = $a [1];
   }} $key = ';
   Extract ($new _tag); $key = ($key)?
   ' $ '. $key. ' => ': '; $s = ' <?php foreach ('. $from. $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 compilation directory if not created then 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->che
  Ck_file_limits ($path, ' R '); if ($r = @fopen ($path, ' r ') = = False) {core::show_error (' stencil file does not have read or Execute permissions, please check!)
  ');
  $content = Fread ($r, FileSize ($path));
  Fclose ($R);
 return $content;
/** * Write file * @param string $filename filename * @param string $content template content * @return filename  * * Private Function Compile_file ($filename, $content, $dir) {if (empty ($filename)) Core::show_error ("{$filename} Crea
  tion failed ");
  $content = $this->body_content ($content)//To the file content Operation//echo ' started compiling ===== ';
  $f = $dir. $filename. $this->tpl_compile_suffix;
  $this->check_file_limits ($f, ' w ');
  if ($fp = @fopen ($f, ' wb ') = = False) {Core::show_error ($f. ' <br/> compile file failed, 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 discarded * @param [$path] [path] * @param [status] [W=write, R=read]/Public Function Check_file
  _limits ($path, $status = ' rw ') {clearstatcache ();
  if (!is_writable ($path) && $status = = ' W ') {core::show_error ("{$path}<br/> does not have write permission, please check.");
  } elseif (!is_readable ($path) && $status = = ' R ') {Core::show_error ("{$path}<br/> does not have Read permission, check."); } elseif ($status = = ' rw ') {//check WirtE and read if (!is_writable ($path) | |!is_readable ($path)) {Core::show_error ("{$path}<br/> does not have write or Read permissions, please check");  
  }}/** * Reads the first line of the compiled template and analyzes the array * @param string $filepath file path * @param number $line rows * @return Returns a string of the specified number of rows
   */* Private Function Get_compile_header ($filepath, $line = 0) {if ($file _arr = @file ($filepath)) = = False) { Core::show_error ($filepath. ' <br/> Read file failed, please check file permissions!
  ');
 return $file _arr[0]; * * */** * Analysis of the date of the header annotation * @param string $cotnent compile file header first line * @return return to the previous date/* Private Function Get_compile_ Header_comment ($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]; * */** * Get template full path and return existing file * @param string $filename filename * @param string $view _path template path * @return/pri vate function Get_tpl ($filename, $view _path) {Empty ($fIlename) && $filename = $this->tpl_name; Traverse template path foreach ($this->conf[' View_path '] as $path) {if ($view _path) {//Find file directly from TPL and directory $tpl _path = $path. $view _p
    Ath
   $view _file_path = $tpl _path. $filename. $this->_tpl_suffix; else {//According to directory, Controller, method start looking for file $view _file_path = ($tpl _path = $this->get_tpl_path ($path))? $tpl _path. $filename-&
   Gt;_tpl_suffix:exit (0); } if (Is_file ($view _file_path)) {//Transfer template path and template name to 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 =
  ') {core::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_di
  R ($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. ') <br/> failed to create directory, please check if you have Write permission!
    ');
   } chmod ($allpath, $mode);
   else {$newdir = $allpath;
 } return true;
  The Public Function __destruct () {$this->vars = null;
 $this->view_path_param = null; }
}

I hope this article will help you with your PHP programming.

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.