PHP-about the template principles and resolutions this content is used as a note for future reference. This content is from the course of Li Yanhui and is not created by myself. If you have any questions, please send a private letter ~ Separating PHP code from static HTML code significantly improves code readability and maintainability. Using the template engine: we refer to the Web template, which is mainly composed of HTML labels.
PHP-about the template principles and resolutions this content is used as a note for future reference. This content is from the course of Li Yanhui and is not created by myself. If you have any questions, please send a private letter ~ Separating PHP code from static HTML code significantly improves code readability and maintainability. Using the template engine: we refer to the Web template, which is mainly composed of HTML labels.
PHP-Principles and Analysis of templates
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 )&&! Emp [this article is from the Internet ( http://www.68idc.cn )] Ty ($ _ 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