Sample code sharing of PHP custom template engine

Source: Internet
Author: User
Tags php foreach php template
This article describes the template engine in PHP in detail. It has good reference value. Let's take a look at the following small series. This article will introduce the template engine in PHP in detail. It has good reference value. Let's take a look at it with the small editor.

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:

 '; // The right delimiter of the dynamic data variable embedded in the template, private $ tpl_vars = array (); // the temporary variable used internally/** saves the value allocated in PHP to the member attribute $ tpl_vars, replace the corresponding variables in the template with @ param string $ tpl_var. a string parameter is required as the subscript of the associated array, @ param mixed $ value corresponding to the variable name in the template requires a scalar value to be assigned to the variable value in 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
 Tpl_vars ["var"]; */'
 Tpl_vars ["$ {1}"];?> ',/* Replace the if string in the template
  
 */'$ This-> stripvtags (\'
 \ ', \' $ {2}
 \ ')',/* Replace the elseif string
 */'$ This-> stripvtags (\'
 \ ', "")',/* Replace the else string
 */'
 ',/* The following two are used to replace the loop identifier in the template with the foreach format */'
 Tpl_vars ["$ {1}"] as $ this-> tpl_vars ["$ {2}"]) {?> $ {3}
 ','
 Tpl_vars ["$ {1}"] as $ this-> tpl_vars ["$ {2}"] =>$ this-> tpl_vars ["$ {3}"]) {?> $ {4}
 ',/* 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")}>

This is the word "red ".

<{Elseif ($ var = "green")}>

This is the word "green ".

<{Else }>< {if ($ size = 20)}>

This is a 20px character.

<{/If }>< {/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

 
   <{$title}> 

Footer. tpl

  

##### <{$author}> #####

Main. tpl

<{Include 'header. tpl '}>
 
 
  
  
<{Loop $ users $ user}>
  
  
     <{Loop $ user $ u }>< {if $ u = "male"}> 
    <{/Loop}> 
   <{/Loop}> 
  
<{Elseif $ u = ""}> <{Else}> <{/If }><{$ u}>
<{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:

 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 the details shared by the sample code of the PHP custom template engine. For more information, see other related articles in the first PHP community!

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.