PHP -- about the principles and resolutions of templates, php -- template parsing _ PHP Tutorial

Source: Internet
Author: User
Tags php foreach
PHP-principles and resolutions of templates, php-template parsing. PHP -- about the principles and resolutions of the template, php -- the template parses this content as a note for future viewing. this content is from the course Li Yanhui, not created by myself, if you have any questions, please use PHP -- about the template principle and parsing, and use php -- template parsing

This content is used as a note for future reference. it is not created by yourself when studying Li Yanhui. if you have any questions, please send a private message ~

Separating PHP code from static HTML code significantly improves code readability and maintainability.

Use the template engine:

The template we call is a Web template. it is a page written in a language consisting of HTML tags. However, there are also ways to express the dynamically generated content (parsing tags ). The template engine is a software library that allows us to generate HTML code from the template and specify the dynamic content to be included.

Features of the template engine:

1. encourage separation: improve the readability and maintainability of more systems.
2. promote the division of labor: enable programmers and artists to focus on their own designs.
3. easier parsing than PHP: compilation files and cache files are loaded faster and consume less resources.
4. Increased Security: The template designer's ability to perform insecure operations can be restricted to avoid accidental access by mistake.

Template processing flowchart

  

Create Template:

1,The folder and file required to create the initial template.

A) index. php main file for compiling business logic.
B) template. inc. php template initialization file for initial template information.
C) the templates Directory stores all template files.
D) the templates_c Directory stores all the compiled files.
E) the cache Directory stores all cached files.
F) the classes Directory stores all class files.
G) the config Directory stores the template system variable configuration file.

  

The following is the source code:

Index. php of the main file

 

// Set the encoding to UTF-8
Header ('content-Type: text/html; Charset = utf-8 ');
// Website root directory
Define ('root _ path', dirname (_ FILE __));
// Store the template folder
Define ('tpl _ dir', ROOT_PATH. '/templates /');
// Compile the folder
Define ('tpl _ C_DIR ', ROOT_PATH.'/templates_c /');
// Cache folder
Define ('cache _ dir', ROOT_PATH. '/CACHE /');
// Define the cache status
Define ('is _ cache', true );
// Set the cache status switch
IS_CACHE? Ob_start (): null;

Include ROOT_PATH. '/schemdes/Templates. class. php ';

$ _ Name = 'square Lil'; $ array = array (1, 2, 3, 4, 5, 6); $ _ tpl = new Templates (); $ _ tpl-> assign ('name', $ _ name); $ _ tpl-> assign ('A', 5> 4 ); $ _ tpl-> assign ('array', $ array); // display $ _ tpl-> display ('index. tpl ');?>

Template File HTML

  <! -- {Webname} -->{Include "test. php "}
  {#} This is a PHP comment. it is not displayed on the HTML page. it will only be displayed in the generated compilation file. {#} I will be indexed. php imports the {$ name} tag through Parser. class. php parsing class to parse it 1
The content here has changed. why?
{If $ a} show skin 1 {else} show skin 2 {/if}
{Foreach $ array (key, value) }{@ key}... {@ value}
{/Foreach}

  

Template class:

// Templates. class. php class Templates {// create a field private $ _ vars = array (); private $ _ config = array (); // Create a constructor named public function _ construct () {if (! Is_dir (TPL_DIR) |! Is_dir (TPL_C_DIR) |! Is_dir (CACHE_DIR) {exit ('Error: Template folder, compilation folder, or cache folder not created! ');} // Obtain the 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 a variable injection method/*** assign () variable injection method * @ param $ _ var name of the variable to be injected, corresponding. variable to be replaced in the tpl file * @ param $ _ values variable value to be injected */public function assign ($ _ var, $ _ values) {if (isset ($ _ var )&&! Empty ($ _ var) {$ this-> _ vars [$ _ var] =$ _ values;} else {exit ('Error: Set the variable name! ') ;}} // Create a display method to display the compiled file public function display ($ _ file) {// set the template file path $ _ tplFile = TPL_DIR. $ _ file; // Determine whether the template file exists if (! File_exists ($ _ tplFile) {exit ('Error: template file does not exist ');} // Set the compilation 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 whether the cached file exists if) & file_exists ($ _ parFile) {// whether the compiled file or template file has been modified if (filemtime ($ _ cacheFile)> = filemtime ($ _ parFile) & filemtime ($ _ parFile)> filemtime ($ _ tplFile) {echo 'cache file content'; echo"
"; Include $ _ cacheFile; return ;}}// determine whether the compiled file exists and whether the template file has been modified if (! File_exists ($ _ parFile) | (filemtime ($ _ parFile) <filemtime ($ _ tplFile) {// introduces the template parsing class require ROOT_PATH. '/includes/Parser. class. php '; // instantiate the object and generate the compilation file $ _ parser = new Parser ($ _ tplFile); // template file $ _ parser-> compile ($ _ parFile ); // compiled file} // load the compiled file include $ _ parFile; if (IS_CACHE) {// Generate the cached file file_put_contents ($ _ cacheFile, ob_get_contents ()); // clear the buffer ob_end_clean (); // load the cache file include $ _ cacheFile ;}}}

Resolution class:

// Parser. class. phpclass Parser {// Obtain the template content private $ _ tpl; // Constructor, initialize the template public function _ construct ($ _ tplFile) {// Determine whether the file exists if (! $ This-> _ tpl = file_get_contents ($ _ tplFile) {exit ('Error: An ERROR occurred while reading the template! ') ;}// Parse the common variable private function parVar () {$ _ pattern ='/\{\$ ([\ w] + )\}/'; if (preg_match ($ _ pattern, $ this-> _ tpl) {$ this-> _ tpl = preg_replace ($ _ pattern ,"
  _ Vars ['$ 1']?> ", $ This-> _ tpl) ;}// parse the IF condition statement private function parIf () {// start with if Mode $ _ patternIf = '/\ {if \ s + \ $ ([\ w] + )\}/'; // end the if Mode $ _ patternEnd = '/\ {\/if \}/'; // else mode $ _ patternElse = '/\ {else \}/'; // Determine whether if (preg_match ($ _ patternIf, $ this-> _ tpl) exists if (preg_match ($ _ patternEnd, $ this-> _ tpl) {// replace the prefix IF $ this-> _ tpl = preg_replace ($ _ patternIf ,"
  _ Vars ['$ 1']) {?> ", $ This-> _ tpl); // replace the end IF $ this-> _ tpl = preg_replace ($ _ patternEnd ,"
  ", $ This-> _ tpl); // determines whether else if (preg_match ($ _ patternElse, $ this-> _ tpl) exists )) {// replace else $ this-> _ tpl = preg_replace ($ _ patternElse ,"
  ", $ This-> _ tpl) ;}} else {exit ('Error: The statement is not closed! ') ;}}// Parse the foreach private function parForeach () {$ _ patternForeach ='/\ {foreach \ s + \ $ (\ w +) \ (\ w +), (\ w +) \}/'; $ _ patternEndForeach ='/\ {\/foreach \}/'; // value $ _ patternVar = '/\ {@ (\ w +) \}/' in foreach; // Determine whether if (preg_match ($ _ patternForeach, $ this-> _ tpl) {// Determine the End flag if (preg_match ($ _ patternEndForeach, $ this-> _ tpl )) {// replace the start with $ this-> _ tpl = preg_replace ($ _ patternForeach ,"
  _ Vars ['$ 1'] as \$ $2 =>\$ $3) {?> ", $ This-> _ tpl); // end of replacement $ this-> _ tpl = preg_replace ($ _ patternEndForeach ,"
  ", $ This-> _ tpl); // replace the value $ this-> _ tpl = preg_replace ($ _ patternVar ,"
  ", $ 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 whether the header file exists if (! File_exists ($ _ file [1]) | empty ($ _ file [1]) {exit ('Error: contains the file does not exist! ');} // Replace content $ this-> _ tpl = preg_replace ($ _ pattern ,"
  ", $ This-> _ tpl) ;}// parse the system variable private function configVar () {$ _ pattern = '/
  /'; If (preg_match ($ _ pattern, $ this-> _ tpl, $ _ file) {$ this-> _ tpl = preg_replace ($ _ pattern ,"
  _ Config ['$ 1']?> ", $ This-> _ tpl) ;}// parse the private function parCommon () {$ _ pattern = '/\{#\}(. *) \{#\}/'; if (preg_match ($ _ pattern, $ this-> _ tpl) {$ this-> _ tpl = preg_replace ($ _ pattern,"
  ", $ This-> _ tpl) ;}// generate the compilation file public function compile ($ _ parFile) {// Parse the template variable $ this-> parVar (); // Parse IF $ this-> parIf (); // Parse comments $ this-> parCommon (); // Parse Foreach $ this-> parForeach (); // Parse include $ this-> parInclude (); // Parse the system variable $ this-> configVar (); // Generate the compilation file if (! File_put_contents ($ _ parFile, $ this-> _ tpl) {exit ('Error: An ERROR occurred while compiling the file! ');}}}

  

Summary: The whole process of the template engine:

1. when the browser requests the index. php file, instantiate the template class object $ _ tpl = new Templates ();

2. when Templates is instantiated, two arrays are generated. one is used to store Template variables, and the other is used to store System Variables. The constructor is used to determine whether a folder exists, at the same time, initialize the system variable array through the XML file

3. use the Templates injection method assign () to inject the index. php content of the variable corresponding to the index. tpl template to the private variable of the template class to complete initialization.

4. display () of the Templates display method. by instantiating the parsing Parser class, the obtained injection variables are parsed (replaced) by the parsing class)

5. after parsing (replace), write the file into the PHP and HTML mixed file.

6. use the display method of the Templates class to output the file:

1. when the display method is executed for the first time, the PHP and HTML hybrid files will be generated to generate pure static cache files.

2. call the cache file to display the page

3. when the browser calls the display method again, it first checks whether to generate a cache file or directly call an existing cache file based on the last modification time of each file.

Important:

1. use regular expressions to replace strings

2. familiar with OOP

  

This content is used as a note for future reference. this content is not created by yourself when studying Li Yanhui. if you have any questions, please...

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.