php--on the principle and analysis of template

Source: Internet
Author: User
Tags html comment php class php template

This content is used as a note for later viewing, this content for learning Li Tinghui courses, not their own, if there is a problem, please private messages ~

Separating the PHP code from the static HTML code makes the code significantly more readable and maintainable.

Using the template engine:

The template we're talking about is a Web template, a page written primarily by a language composed of HTML markup, but there's also a way to represent a dynamic generation of content (parsing tags). The template engine is a software library that allows us to generate HTML code from a template and specify the dynamic content to include.

Features of the template engine:

1. Encouragement of separation: improved readability and maintainability of the system.
2. Promote the division of labor: so that programmers and artists to concentrate on their own design.
3. Easier to parse than PHP: Compile files and cache files load faster and take up less resources.
4. Increased security: can limit the ability of the template designer to do unsafe operation to avoid accidental deletion of erroneous access and so on.

Flowchart for template Processing

  

To create a template:

1 . Create the folders and files needed for the initial template.

A) index.php the master file for writing business logic.
b) template.inc.php template initialization file for initial templates information.
c) The templates directory holds all template files.
d) The Templates_c directory holds all compiled files.
e) The cache directory holds all cached files.
f) The includes directory holds all class files.
g) The Config directory holds the template system variable configuration file.

  

The following is the source code:

Master File index.php

<? PHP//index.php

Set Encoding to UTF-8
Header (' content-type:text/html; Charset=utf-8 ');
Site root directory
Define (' Root_path ', DirName (__file__));
Store Templates folder
Define (' Tpl_dir ', Root_path. /templates/');
Compiling folders
Define (' Tpl_c_dir ', Root_path. /templates_c/');
Cache folder
Define (' Cache_dir ', Root_path. /cache/');
Defining Cache Status
Define (' Is_cache ', true);
Setting the cache status switch
Is_cache? Ob_start (): null;

Include Root_path. ' /includes/templates.class.php ';

  $_name= ' Block Lee '; $array=Array(1,2,3,4,5,6); $_TPL=NewTemplates (); $_TPL->assign (' name ',$_name); $_TPL->assign (' A ', 5>4); $_TPL->assign (' array ',$array); //Show    $_TPL->display (' Index.tpl ');?>

Template file HTML

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">

  

Template class:

         Templates.class.php class Templates {//Create a field that holds an array private $_vars = Array ();    Private $_config = Array ();            Create a constructor method public function __construct () {if (!is_dir (tpl_dir) | |!is_dir (TPL_C_DIR) | |!is_dir (CACHE_DIR)) { Exit (' ERROR: Template folder or compilation folder or cache folder not created!        ‘); }//Get system variable $_sxe = simplexml_load_file (Root_path. '        /config/profile.xml ');        $_taglib = $_sxe->xpath ('/root/taglib ');        foreach ($_taglib as $_tag) {$this->_config["$_tag->name"] = $_tag->value; }}//Create variable injection method/** * Assign () variable injection method * @param $_var the variable name to be injected, corresponding to the variable that needs to be replaced in the. tpl file * @param $_valu            ES the variable value to inject */Public function assign ($_var,$_values) {if (Isset ($_var) &&!empty ($_var)) {                    $this->_vars[$_var] = $_values; }else{exit (' ERROR: Please set the variable name!        ‘); }}//Create a display method to display the compiled file public function display ($_file) {//Set template filePath $_tplfile = Tpl_dir.$_file;        Determine if the template file exists if (!file_exists ($_tplfile)) {exit (' ERROR: template file does not exist '); }//Set compile file name $_parfile = TPL_C_DIR.MD5 ($_file). $_file.        PHP '; Set the cache file name $_cachefile = CACHE_DIR.MD5 ($_file). $_file.        HTML '; Determine the cache status if (Is_cache) {//Determine if the cache file exists if (file_exists ($_cachefile) && file_exists ($_parf ile) {//whether the compiled file has been modified or the template file if (Filemtime ($_cachefile) >=filemtime ($_parfile) && Filem                    Time ($_parfile) >filemtime ($_tplfile) {echo ' below is cache file contents ';                    echo "<br/>";                    Include $_cachefile;                Return }}}//To determine if the compiled file exists and if the template file has been modified if (!file_exists ($_parfile) | | (Filemtime ($_parfile) < Filemtime ($_tplfile))) {//Introduce template parsing class require Root_path. '            /includes/parser.class.php ';  Instantiating an object, generating a compiled file          $_parser = new parser ($_tplfile);//template file $_parser->compile ($_parfile);//post-compilation file}        Loading compilation files include $_parfile;            if (Is_cache) {//Generate cache file File_put_contents ($_cachefile, ob_get_contents ());            Clear buffer Ob_end_clean ();        Loading cache files include $_cachefile; }    }}

Parse class:

Parser.class.phpclass Parser {//Get template content private $_tpl; Constructs a method, initializes the template public function __construct ($_tplfile) {//determines if the file exists if (! $this->_tpl = file_get_contents ($_ Tplfile) {exit (' ERROR: Error reading template!        ‘);    }}//parse ordinary variable private function Parvar () {$_pattern = '/\{\$ ([\w]+) \}/'; if (Preg_match ($_pattern, $this->_tpl)) {$this->_tpl = preg_replace ($_pattern, "<?php echo \ $this->_vars['    $ ']?>, $this-&GT;_TPL);        }}//Parse if condition statement private Function Parif () {//start if mode $_patternif = '/\{if\s+\$ ([\w]+) \}/';        End If mode $_patternend = '/\{\/if\}/';        else mode $_patternelse = '/\{else\}/'; Determines if the if exists if (Preg_match ($_patternif, $this->_tpl)) {//Determines if there is an if End if (Preg_match ($_patternen D, $this->_tpl)) {//Replace the opening if $this->_tpl = preg_replace ($_patternif, "<?php if (\ $this ->_vars[' $ ']) {?> ", $this->_tPL);                Replace the end If $this->_tpl = preg_replace ($_patternend, "<?php}?>", $this-&GT;_TPL); Determine if there is an else if (Preg_match ($_patternelse, $this->_tpl)) {//replace else $                THIS-&GT;_TPL = Preg_replace ($_patternelse, "<?php}else{?>", $this-&GT;_TPL); }}else{exit (' ERROR: statement not closed!            ‘); }}}//parse foreach Private function Parforeach () {$_patternforeach = '/\{foreach\s+\$ (\w+) \ ((\w+) \ (\        w+) \) \}/';        $_patternendforeach = '/\{\/foreach\}/';        The value in foreach $_patternvar = '/\{@ (\w+) \}/'; Determine if there is an if (Preg_match ($_patternforeach, $this->_tpl)) {//Judgment End flag if (Preg_match ($_patternen  Dforeach, $this->_tpl)) {//Replace the beginning $this->_tpl = preg_replace ($_patternforeach, "<?php    foreach (\ $this->_vars['] as \$$2=>\$$3) {?> ", $this-&GT;_TPL);            Replace end $this-&GT;_TPL = Preg_replace ($_patternendforeach, "<?php}?>", $this-&GT;_TPL); Replacement value $this-&GT;_TPL = preg_replace ($_patternvar, "<?php echo \$$1?>", $this->_tpl)            ;            }else{exit (' error:foreach statement not closed ');        }}}//parse include private function Parinclude () {$_pattern = '/\{include\s+\ ' (. *) \ "\}/"; if (Preg_match ($_pattern, $this->_tpl,$_file)) {//Determine if the header file exists if (!file_exists ($_file[1]) | | empty ($_ File[1]) {exit (' ERROR: Contains file does not exist!            ‘); }//replace content $this-&GT;_TPL = preg_replace ($_pattern, "<?php include '";?        > ", $this->_tpl);        }}//parse system variable private function Configvar () {$_pattern = '/<!--\{(\w+) \}-->/'; if (Preg_match ($_pattern, $this->_tpl,$_file)) {$this->_tpl = preg_replace ($_pattern, "<?php echo \ $thi S->_config[' $1 ']?> ", $this-&GT;_TPL);        }}//Parse single-line PHP comment Private function Parcommon () {$_pattern = '/\{#\} (. *) \{#\}/'; if (Preg_match ($_pattern, $this->_tpl)) {$this->_tpl = preg_replace ($_pattern, "<?php/* ($) */?>",        $this-&GT;_TPL);        }}//Generate compile file Public function compile ($_parfile) {//Parse template variable $this->parvar ();        Parse if $this->parif ();        Parse Comment $this->parcommon ();        Parsing foreach $this->parforeach ();        Parsing include $this->parinclude ();        Parsing System Variables $this->configvar (); Generate Compile file if (!file_put_contents ($_parfile, $this->_tpl)) {exit (' ERROR: Compile file build failed!        ‘); }    }}

  

Summary: The entire process of the template engine:

1. When the browser requests the index.php file, instantiate the template class pair like $_tpl = new Templates ();

2, when the templates instantiation, the generation of two arrays, one for the template variable, another to store system variables, through the construction method, determine whether the folder exists, and the XML file to initialize the array of system variables

3, through the template class templates injection method, assign (), the corresponding template Index.tpl the contents of the variable index.php injected into the template class private variables, complete initialization

4, template class templates display method displays () by instantiating the parsing class parser, the injected variable is parsed by parsing the class (that is, replacing)

5. After parsing (replacing), write the file to PHP, HTML mixed file

6, through the Templates class display method to output the file:

1, the first time to execute the display method, will be the PHP, HTML mixed files, generated a pure static cache file

2. Call the cache file to display the page

    3, when the browser calls the display method again, the first according to the last modification time of each file, determine whether to regenerate the cache file or directly call the existing cache file

Focus:

1. Replacing strings with regular expressions

2, familiar with OOP

  

php--on the principle and analysis of template

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.