PHP custom template engine and PHP custom template engine
Previous
In most project teams, developing a Web program involves the following process: After the planning document is submitted, the front-end engineer creates a website appearance model and then delivers it to the back-end engineer, they use the back-end code to implement the program logic, and use the appearance model to make the basic architecture, and then the project is returned to the front-end engineer for further improvement. In this way, the project may return several times between the backend engineer and the front-end engineer. Because backend engineers do not intervene in any related HTML tags, and do not need to mix the front-end code with the back-end code. Front-end engineers only need configuration files, dynamic blocks, and other interface parts, and do not need to access complicated back-end code. Therefore, it is very important to have a good template support. This article will introduce the template engine in PHP in detail
Overview
What is a website template? Accurately speaking, it refers to a website page template, that is, each page is only a plate, including the structure, style, and page layout. It is a template for creating webpage content, it can also be understood as an existing Web framework. You can replace the original content in the template with the dynamic content from the server-side database to ensure that the page style is consistent.
PHP is an HTML embedded script language executed on the server. Therefore, for most Web applications developed by PHP, the initial development template is mixed layer data programming. Although the MVC design mode can forcibly separate the application logic from the webpage presentation logic, it only separates the application input, processing, and output, and the webpage presentation logic (view) there will also be strong coupling between HTML code and PHP programs. PHP script writers must be web designers and PHP developers.
There are already many solutions to completely separate website page design from PHP applications. These solutions are called "template engines" and are gradually eliminating the challenges arising from the lack of hierarchical separation. The purpose of the template engine is to achieve the logic separation function mentioned above. It enables program developers to focus on data control or function fulfillment. Therefore, the template engine is suitable for the company's Web development team so that everyone can use its expertise.
The core of the template engine technology is relatively simple. You only need to specify the front-end page as a template file and add dynamic content in the template file, such as database output and user interaction, it is defined as a "variable" contained in a special "delimiter" and placed in the corresponding position in the template file. When a user browses the template, the PHP script opens the template file and replaces the variables defined in the template file. In this way, when the special variables in the template are replaced with different dynamic content, the required page will be output.
Currently, there are many mature templates that can be applied in PHP, such as Smarty, PHPLIB, and IPB. Using these template engines written in PHP can make the code context clearer and the structure more rational. It also makes website maintenance and updates easier, creates a better development environment, and makes development and design work easier to combine. However, no PHP template is the most appropriate and perfect. Because PHP templates are popular and not developed for someone. If you fully recognize the advantages and disadvantages of templates based on a clear understanding of the features and applications of templates, you can determine whether to use the template engine or which template engine to use.
Custom template engine class
The Custom template engine can better understand the working mechanism of the template engine and prepare for learning Smarty. More importantly, your own PHP template engine is never fixed and can be tailored to the project's needs.
In the following example, a simple template engine is created based on the template engine concept described earlier, which can be used to process the basic functions of the template. For example, variable replacement, branch structure, array looping, and nesting between templates are as follows:
<? Php/** file: mytpl. class. the php class name MyTpl is a custom template engine that loads and parses the template file through this class object and outputs the parsed result */class Mytpl {public $ template_dir = 'templates '; // define the template file storage directory public $ compile_dir = 'templates _ C'; // define the file storage directory public $ left_delimiter = '<{' After the template engine is combined {'; // The left delimiter public $ right_delimiter = '}>' That embeds dynamic data variables in the template '; // The right separator private $ tpl_vars = array () for embedding dynamic data variables in the template (); // temporary variables used internally/** Save the value allocated in PHP to the member attribute $ tpl_vars to replace the corresponding variables in the template @ param st Ring $ tpl_var requires a string parameter as the subscript of the associated array. to correspond to the variable name in the template @ param mixed $ value, a scalar value is required, value used to allocate variables to the template */function assign ($ tpl_var, $ value = null) {if ($ tpl_var! = '') $ This-> tpl_vars [$ tpl_var] = $ value;}/** load the template file in the specified directory, and save the generated combined file with the replaced content to another specified directory. @ param string $ fileName provides the template file name */function display ($ fileName) {/* Find the template file in the specified directory */$ tplFile = $ this-> template_dir. '/'. $ fileName;/* if the template file to be processed does not exist, exit and report an error */if (! File_exists ($ tplFile) {die ("template file {$ tplFile} does not exist! ");}/* Get the template file of the combination. All content in this file is replaced */$ comFileName = $ this-> compile_dir. "/com _". $ fileName. '. php ';/* to determine whether the replaced file exists or exists but has been changed, you need to re-create */if (! File_exists ($ comFileName) | filemtime ($ comFileName) <filemtime ($ tplFile )) {/* call the internal replacement Template Method */$ repContent = $ this-> tpl_replace (file_get_contents ($ tplFile )); /* Save the script file after the system combination */file_put_contents ($ comFileName, $ repContent );} /* include the processed template file and output it to the client */include ($ comFileName);}/** private method used internally, use a regular expression to replace the statements in the template file '<{}>' with the corresponding values or the PHP code @ param string $ content provides all the content strings read from the template file @ return $ repContent returns the replaced string */p Rivate function tpl_replace ($ content) {/* escape special characters that affect regular expressions in the left and right delimiters, for example, <{}> escape \\{\}\> */$ left = preg_quote ($ this-> left_delimiter ,'/'); $ right = preg_quote ($ this-> right_delimiter ,'/'); /* pattern array of Regular Expressions matching various identifiers in the template */$ pattern = array (/* matches the variables in the template, for example, "<{$ var}> "*/'/'. $ left. '\ s * \ $ ([a-zA-Z _ \ x7f-\ xff] [a-zA-Z0-9 _ \ x7f-\ xff] *) \ s *'. $ right. '/I',/* matches the if identifier in the template, for example, "<{if $ col =" sex "}>< {/if}> "*/'/'. $ l Eft. '\ s * if \ s * (. + ?) \ S * '. $ right.' (. + ?) '. $ Left. '\ s * \/if \ s *'. $ right. '/ies',/* matches the elseif identifier, for example, "<{elseif $ col =" sex "}> "*/'/'. $ left. '\ s * else \ s * if \ s *(. + ?) \ S *'. $ right. '/ies',/* matches the else identifier, for example, "<{else}> "*/'/'. $ left. '\ s * else \ s *'. $ right. '/is',/* is used to match the loop identifier in the template and traverse the values in the array, for example, "<{loop $ arrs $ value }>< {/loop}> "*/'/'. $ left. '\ s * loop \ s + \ $ (\ S +) \ s + \ $ ([a-zA-Z _ \ x7f-\ xff] [a-zA-Z0-9 _ \ x7f-\ xff] *) \ s *'. $ right. '(. + ?) '. $ Left. '\ s * \/loop \ s *'. $ right. '/is',/* is used to traverse the keys and values in the array, for example, "<{loop $ arrs $ key = >$ value }>< {/loop}> "*/'/'. $ left. '\ s * loop \ s + \ $ (\ S +) \ s + \ $ ([a-zA-Z _ \ x7f-\ xff] [a-zA-Z0-9 _ \ x7f-\ xff] *) \ s * => \ s * \ $ (\ S +) \ s *'. $ right. '(. + ?) '. $ Left. '\ s * \/loop \ s *'. $ right. '/is',/* matches the include identifier, for example,' <{include "header.html"}> '*/'/'. $ left. '\ s * include \ s + [\ "\']? (. + ?) [\ "\ ']? \ S *'. $ right. '/ie');/* replace the string array matching the regular expression in the template */$ replacement = array (/* replace the variable in the template <? Php echo $ this-> tpl_vars ["var"]; */'<? Php echo $ this-> tpl_vars ["$ {1}"];?> ',/* Replace the if string in the template <? Php if ($ col = "sex") {?> <? Php }?> */'$ This-> stripvtags (\' <? Php if ($ {1}) {?> \ ', \' $ {2} <? Php }?> \ ')',/* Replace the elseif string <? Php} elseif ($ col = "sex") {?> */'$ This-> stripvtags (\' <? Php} elseif ($ {1}) {?> \ ', "")',/* Replace the else string <? Php} else {?> */'<? Php} else {?> ',/* The following two are used to replace the loop identifier in the template with the foreach format */' <? Php foreach ($ this-> tpl_vars ["$ {1}"] as $ this-> tpl_vars ["$ {2}"]) {?> $ {3} <? Php }?> ',' <? Php foreach ($ this-> tpl_vars ["$ {1}"] as $ this-> tpl_vars ["$ {2}"] =>$ this-> tpl_vars ["$ {3} "]) {?> $ {4} <? Php }?> ',/* Replace the include string */' file _ get_contents ($ this-> template_dir. "/$ {1}") ');/* use the regular expression replacement function to process */$ repContent = preg_replace ($ pattern, $ replacement, $ content ); /* if there is another identifier to be replaced, recursively call it to replace it again */if (preg_match ('/'. $ left. '([^ ('. $ right. ')] {1 ,})'. $ right. '/', $ repContent) {$ repContent = $ this-> tpl_replace ($ repContent);}/* return the replaced string */return $ repContent ;} /** internal private method used to replace the variables used in the condition statement with the corresponding value @ param string $ expr @ Param string $ statement indicates the end mark of the Condition statement in the template. @ return strin returns the */private function str1_tags ($ expr, $ statement = '') {/* match the variable's regular */$ var_pattern = '/\ s * \ $ ([a-zA-Z _ \ x7f-\ xff] [a-zA-Z0-9 _ \ x7f -\ xff] *) \ s */is ';/* replace the variable with the value */$ expr = preg_replace ($ var_pattern,' $ this-> tpl_vars ["$ {1}"] ', $ expr);/* replace the quotation mark escape characters in the Start mark */$ expr = str_replace ("\\\" "," \ "", $ expr ); /* replace the quotation marks in the statement body and end mark */$ statement = Str_replace ("\" "," \ "", $ statement);/* returns */return $ expr after connecting the processed Condition statement. $ statement ;}}?>
Among the multiple methods declared in the Mytpl class, except the encapsulated methods, only two public methods assign () and display () can be used after the object is created. The assign () method is used to allocate data in the PHP script to the corresponding variables in the template, and the display () method is used to load the template files under the specific templates directory to the PHP script. At the same time, use "<{" and ">" in the template file to mark the declared custom template statements, match them and replace them with the corresponding PHP syntax format, save the replaced content in the specified templates_c directory. At runtime, You need to compile a php file that is not a template technology, and save it as a template file name prefixed with "com _" and ". php" extension. Then, use the include () function to include the processed template file and use PHP to parse it and send it to the client.
Use the template engine
It is easier to use a custom template engine, which is a custom syntax format. But remember that all popular templates and traditional solutions follow the same set of core implementation principles, that is, they are the same as programming languages, after learning one language, you can easily master other languages. The main reason for using the template engine is to separate front-end engineers from backend engineers. Therefore, the template engine is not only used by backend engineers, but also by front-end engineers.
1. Use of the template engine by backend engineers
The PHP script contains the file where the template engine class is located. As follows:
Require ("mytpl. class. php"); // contains the template engine class, which is equivalent to template engine installation.
Create an object of the template engine class and initialize and assign values to some member attributes. As follows:
$ Tpl = new MyTpl (); // create an object of the template engine class. You can also initialize the member based on the parameter.
Use the assign () method in the template engine object to allocate dynamic data (including scalar and array data, such as the data array obtained from the database table) to the template file, this method can be used multiple times to allocate any number of variables to the template. As follows:
$ Tpl-> assign ("var", "this is a value"); // you can allocate scalar Data Multiple times. $ tpl-> assign ("arr ", array (1, 2), array ("a", "B"); // You can also assign an array that includes multi-dimensional arrays.
In the PHP script, by calling the display () method in the template object and passing in the template file name as a parameter, the corresponding template file in the specified directory will be loaded to the PHP script. Parse the custom syntax in the template by using the replacement method in the template engine, and then output the processed template. As follows:
$ Tpl-> display ("test. tpl"); // The parameter "test. tpl" is the template file in a specific directory.
2. Use of the template engine by front-end engineers
The front-end engineer needs to store the template file to the specified directory, which is specified by using the $ template_dir attribute in the template object, the default setting is the "templates" directory under the current directory. In addition, the name of the template file can be set with a suffix, such as index.tpl1_test.htm and header. tp.
Template files are purely static files written using HTML, CSS, javascript, and other Web Front-end languages. However, you can define a variable (similar to the variable format in PHP) between the "<{" and "}>" delimiters in the template file ), this variable can accept and output dynamic data allocated by the PHP script. The "<{" and "}>" delimiter pairs used in the template can also be modified in the template engine class according to your personal interests. As follows:
Name: <{$ name}>, age: <{$ age}>, Gender: <{$ sex}> // use placeholders in the template
If the PHP script assigns an array to the template, you can also traverse the template, or you can traverse multi-dimensional arrays through nesting. The <{loop}> tag pair defined in the template engine is used in a similar way as the syntax format of the foreach structure in PHP. As follows:
<{Loop $ arr $ value}> // traverses the element value in the element value array of $ arr <{$ value}> // traverses the value in the output element each time <{/loop }> // traverse the end mark of the array in the template <{loop $ arr $ key => $ value}> // traverse the element subscript in the array $ arr and element value array. key <{$ key}> // element value in the subscript array of each output element <{$ value}> // value in each output element <{/loop}>/ /traverse the end mark of the array in the template <{loop $ arr $ value}> // traverse the element value in the array $ arr <{loop $ arr $ data}> // use nesting mark to traverse the element values in the two-dimensional array <{$ value}> // traverse the value of the output element <{/loop}> // traverse the inner layer of the array in the template <{/loop}> // traverse the outer end mark of the array in the template.
The template engine can also parse the branch structure written with special tags in the template file. The syntax style is similar to the branch structure of PHP. By using the <{if}> label in the template file to select the structure, you can also select the structure of multiple branches and nested branches. Example:
<{If ($ var = "red")}> <p style = "color: red "> This is the word" red "</p> <{elseif ($ var =" green ")}> <p style =" color: green "> This is the word" green "</p> <{else}> <{if ($ size = 20)}> <p style =" font-size: 20 "> This Is A 20px font </p> <{/if}>
The Custom template engine also adds the function to include other template files in the template file. You can use the <{include 'sub-template filename '}> mark to include the sub-template into the current template. You can also include another sub-template in the sub-template. As follows:
<{include 'other.tpl' }>
Use Case Analysis
By loading the template engine in a program, you can separate the front-end language from the back-end language code. First, obtain the data stored in the database in the PHP program, then allocate the data by loading the template engine, and then load and process the template file through the template engine and then output it. Therefore, the PHP program only creates dynamic data, loads the template engine, and allocates dynamic data to the template to complete the work of the PHP program. However, the template design requires independent front-end engineers to use HTML, CSS, javascript, and other front-end page design languages. In addition, you also need to use the tags that can be parsed by the template engine to reference the dynamic data allocated in PHP in the template.
1. Database Design
Assume that the database server is on the "localhost" host, and the connection usernames and passwords are "admin" and "123456" respectively, and create a database named "mydb" on the server, create a User table named "User" in the database. The SQL statement used to create the table is as follows:
CREATE TABLE User( id SMALLINT(3) NOT NULL AUTO_INCREMENT, name VARCHAR(10) NOT NULL DEFAULT '', sex VARCHAR(4) NOT NULL DEFAULT '', age SMALLINT(2) NOT NULL DEFAULT '0', email VARCHAR(20) NOT NULL DEFAULT '', PRIMARY KEY (id));
After the User table is created, you can insert some data into the table as an example. The SQL query statement is as follows:
Insert into User (name, sex, age, email) VALUES ("a", "male", 27, "a@a.com"), ("B", "female", 22, "B @ B .com"), ("c", "female", 30, "c@c.com"), ("d", "female", 24, d@d.com );
2. template design
The template design should not contain any PHP code, which can be completed by the front-end personnel. In the Custom template engine, it specifies that the template file is to be searched in the specified directory. This specific directory can be specified when the template engine object is created, you can also use the default directory settings. By default, you can store template files under the "templates" directory in the current directory. In this example, three template files, main. tpl, header. tpl, and footer. tpl, are stored in the default directory settings. The code for these three template files is as follows:
Header file header. tpl of the template
<!DOCTYPE html>
Footer. tpl
<div style="width:200px;margin: 0 auto;">##### <{$author}> #####</div> </body>
Main. tpl
<{Include 'header. tpl '}> <table border = "1" align = "center" width = "500"> <{loop $ users $ user}> <tr> <{loop $ user $ u }>< {if $ u = "male"}> <td style = "color: green "> <{elseif $ u =" "}> <td style =" color: red "> <{else}> <td> <{/if}> <{$ u}> </td> <{/loop}> </tr> <{/ loop }></table> <{include 'footer. tpl '}>
File main. tpl is the main template file. In this file, use <{include "header. tpl "}>and <{include" footer. tpl "}> the two tags are located at the top and bottom of the file, and the independent header and tail template files are included in the main template file. Use the <{tableName}> tag in the file to obtain the dynamically allocated table name from PHP, and use the double-layer <{loop}> tag nesting, traverse the two-dimensional array $ Users dynamically allocated from PHP in the database, and use the Condition Selection tag in the <{loop}> tag <{if}> combination, set the background of the table whose gender is "male" in the data to red and other judgments. The header template file header. tpl and the tail template file footer. tpl can also obtain the data dynamically allocated to the template from PHP.
3. PHP Programming
With the use of the template engine, PHP programmers only need one language for coding, you do not need to use HTML, CSS, javascript, and other page design languages to complete front-end work. The following is a php script file named index. PHP, which is in the same directory as the file mytpl_class.php where the template engine class is located. The Code is as follows:
<? Php // contains the template engine class include "mytpl. class. php "; // create a template engine object $ tpl = new Mytpl; // connect to the database $ pdo = new PDO (" mysql: host = localhost; dbname = mydb ", "admin", "123456"); // execute the SQL statement $ stmt = $ pdo-> prepare ("select id, name, sex, age, email from User order by id "); $ stmt-> execute (); $ data = $ stmt-> fetchAll (PDO: FETCH_ASSOC ); // This is the dynamic data obtained from the database. You need to display $ tpl-> assign ('title', "Custom template engine") in the template "); $ tpl-> assign ('auto', "matches"); $ tpl-> assign ('Users', $ data); $ tpl-> display ("main. tpl");?>
In the above PHP script file, connect to the MySQL server through the PDO object, obtain all records in the User table, and save them in the form of a two-dimensional array variable of PHP in the variable data. Then, use the "mytplclss. php" file in the current directory to create and initialize the object data of the template engine class. Then, use the "mytplclss. php" file in the current directory to create and initialize the tpl object of the template engine class. Then, use the assign () method in the object to allocate some data to the template, and then use the display () method in the object to load the main. tpl template file. Replace the special variables marked in the template with the dynamic data allocated from PHP. After processing, the output template page is displayed. The output result of the page is as follows:
It is very difficult to create a custom PHP template engine based on different conditions, such as time and experience. In fact, it is not necessary to re-construct a PHP template, but to select a PHP template that is closest to you.
The above is all the content of this article. I hope this article will help you in your study or work. I also hope to provide more support to the customer's home!