PHP to make a simple template engine _php instance

Source: Internet
Author: User
Tags create index md5 mkdir php class php foreach php template require

PHP template engine is a PHP class library, using it can make the PHP code and HTML code to separate, so that the readability and maintenance of the code has been significantly improved. And the advantage of doing so is that the artist concentrates on designing the HTML foreground page, and the programmer concentrates on writing the PHP business logic. As a result, the modular engine is well suited to the company's web development team, enabling everyone to develop their expertise

Let's take a look at how simple it is to implement the PHP template engine

parser.class.php

<?php/** * Template Resolution class */class Parser {//field, receive template file content private $_tpl;
      Constructs a method that gets the template file content Public function __construct ($_tplfile) {if (! $this->_tpl = file_get_contents ($_tplfile)) {
    Exit (' ERROR: template file read error ');
    }///parse ordinary variable private function Parvar () {$_patten = '/<!--\s+\{\$ ([\w]+) \}\s+-->/'; if (Preg_match ($_patten, $this->_tpl)) {$this->_tpl = preg_replace ($_patten, "<?php echo \ $this->_vars[" $ '];?
    > ", $this->_tpl);
    }//Parse if statement private function Parif () {$_pattenif = '/<!--\s+\{if\s+\$ ([\w]+) \}\s+-->/';
    $_pattenelse = '/<!--\s+\{else\}\s+-->/';
    $_pattenendif = '/<!--\s+\{\/if\}\s+-->/'; if (Preg_match ($_pattenif, $this->_tpl)) {if (Preg_match ($_pattenendif, $this->_tpl)) {$this-&GT;_TPL
        = Preg_replace ($_pattenif, "<?php if (\ $this->_vars[']) {?>", $this-&GT;_TPL); $this-&GT;_TPL = preg_replace ($_pattenendif, <?php}?>", $this-&GT;_TPL); if (Preg_match ($_pattenelse, $this->_tpl)) {$this->_tpl = preg_replace ($_pattenelse, "<?php}else{?>"
        , $this-&GT;_TPL); }}else{Echo ' error:if statement not closed!
      ';
    The//php annotation resolves private function Parcommon () {$_pattencommon = '/<!--\s+\{#\} (. *) \{#\}\s+-->/'; if (Preg_match ($_pattencommon, $this->_tpl)) {$this->_tpl = preg_replace ($_pattencommon, "<?php * * *
    ?> ", $this-&GT;_TPL); }//Resolve foreach statement private function Parforeach () {$_pattenforeach = '/<!--\s+\{foreach\s+\$ ([\w]+) \ ([\w]+
    ), ([\w]+) \) \}\s+-->/';
    $_pattenforeachend = '/<!--\s+\{\/foreach\}\s+-->/';
    $_pattenforeachvalue = '/<!--\s+\{@ ([\w]+) \}\s+-->/'; if (Preg_match ($_pattenforeach, $this->_tpl)) {if (Preg_match ($_pattenforeachend, $this->_tpl)) {$this -&GT;_TPL = Preg_replace ($_pattenforeach, "<?php foreach (\ $this->_vars['] as \$$2=>\$$3){?> ", $this-&GT;_TPL);
        $this-&GT;_TPL = preg_replace ($_pattenforeachend, "<?php}?>", $this-&GT;_TPL); if (Preg_match ($_pattenforeachvalue, $this->_tpl)) {$this->_tpl = preg_replace ($_pattenforeachvalue, "< ? php echo \$$1;?
        > ", $this->_tpl); }}else{Echo ' error:foreach statement not closed!  
      '; }}//Resolve include method Private function Parinclude () {$_patteninclude = '/<!--\s+\{include\s+file=\ ' ([\w\.
    \-]+) \ "\}\s+-->/"; if (Preg_match ($_patteninclude, $this->_tpl,$_file,$_file)) {if (!file_exists ($_file[1)) | | Empty ($_file)) {echo ' ERROR: Error containing file!
      '; } $this->_tpl = Preg_replace ($_patteninclude, <?php include ' $ ';?
    > ", $this->_tpl);
    }//Parse system variable method private function Parconfig () {$_pattenconfig = '/<!--\s+\{([\w]+) \}\s+-->/'; if (Preg_match ($_pattenconfig, $this->_tpl)) {$this->_tpl = preg_replace ($_pattenconfig, "<?php echo \ $this- >_config[' $ '];?
    > ", $this->_tpl);
    Compile ($_path) {//parsing template file $this->parvar ();
    $this->parif ();
    $this->parforeach ();
    $this->parinclude ();
    $this->parcommon ();
    $this->parconfig (); Generate compile file if (! file_put_contents ($_path, $this->_tpl)) {exit (' ERROR: Compile file build Error!
    ');

 }}}?>

Templates.class.php

<?php/** * Template class */class Templates {//injection variable private $_vars = Array ();
  Save system variable Array field private $_config = Array (); Create a construct method to detect whether the individual directories have public function __construct () {if (! Is_dir (tpl_dir) | |! Is_dir (TPL_C_DIR) | |! Is_dir (CA CHE) | | !is_dir (CONFIG)) {echo ' ERROR: Template directory or compilation directory, cache directory does not exist! Automatic Creation! '."
      <br/> ";
        if (!is_dir (Tpl_dir)) {mkdir (tpl_dir); echo ' template catalog '. Tpl_dir. ' Build '. '
      <br/> ";
        } if (!is_dir (Tpl_c_dir)) {mkdir (tpl_c_dir); echo ' Compile directory '. Tpl_c_dir. ' Build '. '
      <br/> ";
        } if (!is_dir (cache)) {mkdir (cache); echo ' Cache directory '. CACHE. ' Build '. '
      <br/> ";
        } if (!is_dir (config)) {mkdir (config); echo ' Cache directory '. CONFIG. ' Build '. '
      <br/> ";
    } exit (); //Save system variable $_sxe = simplexml_load_file (CONFIG. '
    /config.xml ');
    $_taglib = $_sxe->xpath ('/root/taglib '); foreach ($_taglib as $_tag) {$this->_config["$_tag->name"] = $_TAG-&GT;value; The//assign () method, which is used to inject the variable public function assign ($_var,$_value) {//$_var The variable name//$_value in the synchronization template to represent the value if (ISS
    ET ($_var) &&!empty ($_var)) {$this->_vars[$_var] = $_value; }else{exit (' ERROR: set template variable!
    ');
    }//display () method public function display ($_file) {$_tplfile = Tpl_dir. $_file; Determine if the file exists if (! file_exists ($_tplfile)) {echo ' ERROR: Template file does not exist! Automatically create INDEX.TPL template files!
      ';
      File_put_contents ($_tplfile, ' Index ');
    Exit (); //Generate compilation file $_path = Tpl_c_dir.md5 ($_file). ' -'. $_file. '.
    PHP '; Cached File $_cachefile = CACHE.MD5 ($_file). ' -'. $_file. '.
    HTML '; When running the same file for the second time, load the cached file directly (Is_cache) {//To determine whether the cached file and the compiled file exist if (file_exists ($_cachefile) &&file_exists ($ _path)) {//Determine if the template file has been modified if (Filemtime ($_path) >=filemtime ($_tplfile) &&filemtime ($_cachefile) >
          =filemtime ($_path)) {include $_cachefile;
          Echo ' <!--cache--> ';Return If the compilation file does not exist or the file changes, regenerate if (!file_exists ($_path) | | Filemtime ($_path) <filemtime ($_tplfile)) {require root_path. '
      /class/parser.class.php ';
      The constructor method is an incoming template file address $_parser = new parser ($_tplfile);
    Incoming compile file address $_parser->compile ($_path);
    //Load compilation file include $_path;
      if (Is_cache) {//Get buffer Data file_put_contents ($_cachefile,ob_get_contents ());
      Clear buffer Ob_end_clean ();
    Load cache file include $_cachefile;

 }}}?>

templates.php

<?php
//Set character encoding UTF-8
header (' Content-type:text/html;charset=utf-8 ');
 
Web site root directory
define (' Root_path ', DirName (__file__));
 
Store Template folder
define (' Tpl_dir ', Root_path. ') /templates/');
 
Compile folder
define (' Tpl_c_dir ', Root_path. ') /templates_c/');
 
Cache folder
define (' cache ', Root_path. ') /cache/');
 
System Variable Configuration directory
define (' CONFIG ', Root_path. ') /config/');
 
Whether to open buffer
define (' Is_cache ', false);//false
 
//judge if you need to open
Is_cache? Ob_start (): null;
 
Introduce template class
require Root_path. ' /class/templates.class.php ';
 
Instantiation template class
$_tpl=new Templates ();
 
$_tpl->display (' Index.tpl ');
? >

Templates/index.tpl

<! DOCTYPE html> 
Related Article

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.