Sample code sharing for PHP's custom template engine

Source: Internet
Author: User
Tags closing tag php foreach php template scalar
This article describes the template engine in PHP in detail. Has a good reference value. Let's take a look at the little series.

Previous words

In most project groups, the process of developing a Web application is that the front-end engineer makes a visual model of the site and then hands it back to the backend engineer, which uses the back-end code to implement the program logic while using the façade model to make the basic architecture. Then the project was returned to the front-end engineer to continue perfecting. In this way, the project may come back and forth several times between the back-end engineer and the front-end engineer. Since the backend engineer does not interfere with any related HTML tags, it does not require a mix of front-end code and back-end code. Front-end engineers only need configuration files, dynamic chunks, and other interface parts, without having to touch the intricacies of back-end code. Therefore, it is important to have a good template support at this time. This article will cover the template engine in PHP in detail

Overview

What is a site template? Accurately speaking, refers to the Site page template, that is, each page is only a plate, including structure, style and page layout, is to create a template for the content of the Web page, can also be understood as an existing Web page framework. You can replace the contents of the template with dynamic content from the server-side database to keep the page style consistent

PHP is a kind of HTML embedded in the server-side scripting language, so most of the PHP developed Web applications, the initial development template is the mixed layer of data programming. Although the application logic of the program can be forced separated from the Web page rendering logic through the MVC design pattern, it only separates the input, processing and output of the application, and the Web page rendering logic (view) also has the strong coupling between the HTML code and the PHP program. PHP scripts must be written by both Web designers and PHP developers.

There are now many solutions that can separate the page design of a Web site from the PHP application almost completely. These solutions are called "template engines," and they are gradually eliminating the challenges posed by the lack of hierarchical separation. The purpose of the template engine is to achieve the above mentioned logical separation function. It enables program developers to focus on the control of the data or the achievement of the function. As a result, the template engine is well suited to the company's web development team, enabling everyone to develop their expertise

The core of template engine technology is relatively simple. As long as the front page is designated as a template file, and the dynamic content in this template file, such as database output, user interaction and other parts, defined as the use of special "delimiter" contains the "variable", and then placed in the template file in the corresponding location. When the user browses, the template file is opened by the PHP script and replaced with the variables defined in the template file. Thus, when special variables in the template are replaced with different dynamic content, the desired page is output

At present, there are many more mature templates that can be applied in PHP, such as Smarty, Phplib, IPB, etc. dozens of kinds. With these template engines written in PHP, you can make the code context clearer and the structure more rationalized. It can also make it easier to maintain and update the site, creating a better development environment that makes development and design work easier to combine. However, no PHP template is the most appropriate and perfect. Because PHP template is a popular thing, not for someone to develop. If you can get a clear understanding of the characteristics and application of the template, and fully understand the advantages and disadvantages of the template, you can know whether to choose the template engine or choose which template engine to use

Custom Template engine Classes

The custom template engine can better grasp 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 needs of the project

In the following example, the template engine concept described earlier creates a simple template engine of its own that can be used to handle the basic functionality of a template. For example: variable substitution, branch structure, array looping, and nesting of templates, as shown below:

<?php/** file:mytpl.class.php class named Mytpl is a custom template engine that loads the template file through the class object and resolves it, outputting the parsed result output */class Mytpl {public $template _dir =  ' Templates ';  Defines the directory where template files are stored public $compile _dir = ' Templates_c ';   Defines the file directory public $left _delimiter = ' <{' when combined with the template engine;   Embed the left-bound symbol of the dynamic Data variable in the template public $right _delimiter = '}> ';    Embed the right-bound symbol for the Dynamic Data variable in the template private $tpl _vars = Array ();    The temporary variable/** used internally saves the assigned value in PHP to the member property $tpl_vars, which replaces the corresponding variable in the template @param string $tpl _var requires a string parameter to be the index of the associative array, corresponding to the variable name in the template         @param mixed $value need a scalar type value to assign to the value of the variable in the template */function assign ($tpl _var, $value = null) {if ($tpl _var! = ")  $this->tpl_vars[$tpl _var] = $value; /** loads the template file under the specified directory and stores the replaced content generation combination file in another specified directory @param string $fileName provide the file name of the template */function display ($    FileName) {/* Find the template file in the specified directory */$tplFile = $this->template_dir. '/'. $fileName; /* If the template file that needs to be processed does not exist, exit and report the error */if (!file_exists ($tplFile)) {die ("template file {$tplFile} does not exist!)   "); }/* Gets the combined template file, and the contents of the file are replaced by */$comFileName = $this->compile_dir. " /com_ ". $fileName.    PHP '; /* To determine if the replaced file exists or exists but has changed, it needs to be recreated */if (!file_exists ($comFileName) | | filemtime ($COMFILENAME) < Filemtime ($tplFile))     {/* Call 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);       }/* Contains the processed template file output to client/include ($comFileName); }/** The private method used internally, use regular expressions to replace the statement in the template file ' <{}> ' with the corresponding value or PHP code @param string $content provide a full string of content that is read from the template file @return $re Pcontent returns the replaced string */Private Function Tpl_replace ($content) {/* will be left and right in the bounding symbol, there are special symbols that affect the regular escape for example, <{}> escape \<\{\}\& Gt   */$left = Preg_quote ($this->left_delimiter, '/');   $right = Preg_quote ($this->right_delimiter, '/'); /* The pattern array of regular expressions that match the 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, such as "<{if $col = =" Sex "}> <{/if}> "* */". $left. ' \s*if\s* (. +?) \s* '. $right. ' (.+?)'. $left. ' \s*\/if\s* '. $right. ' /ies ',/* matches ElseIf identifiers, such as "<{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 to iterate through the values in the array, such as "<{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 iterate through the keys and values in the array, such as "<{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 that matches the regular expression from 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} else  if ($col = = "Sex") {?> */' $this->stripvtags (\ ' <?php} elseif (${1}) {? >\ ', "") ',/* Replace 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->tp l_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 regular replace function to process */$repContent = Preg_replace ($pattern, $replacement, $content); /* If there is an identity to replace, recursively call yourself to replace the */if (Preg_match ('/'. $left. ([^ ('. $right. ')] {1,}) '. $right. ' /', $repContent)) {$repConteNT = $this->tpl_replace ($repContent);            }/* Returns the replaced String */return $repContent; The private method used internally by/** is used to replace the variable used in the conditional statement with the corresponding value @param string $expr provides the opening tag of the conditional statement in the template @param string $statement provides the end label of the conditional statement in the template Remember @return Strin returns the processed conditional statement ($expr, $statement = ') {/* match variable's regular/$var _patt    Ern = '/\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 marks in the opening tag with the */$expr = Str_replace ("\\\" "," \ "", $expr);    /* Replace the quotation marks in the statement body and closing tag */$statement = Str_replace ("\\\" "," \ "", $statement);          /* Returns $EXPR after the processed conditional statement is connected. $statement; }}?>

In more than one method declared in the Mytpl class, only two public methods assign () and display () can be wither after the object is created, in addition to the encapsulated method. where the Assign () method is used to assign the data in the PHP script to the corresponding variable in the template, the display () method is used to load the template file in the specific templates directory into the PHP script. At the same time, the template file using the "<{" and ">>" tag declaration of the custom template statements, matching and replace the corresponding PHP syntax format, and then save the replaced content in a specific Templates_c directory. Also compile the PHP file as a non-template technology at run time and save it as a template file name with the "com_" prefix and the ". PHP" extension. The included () function will then include the processed template file and send it to the client using PHP parsing

Using the template engine

Using a custom template engine is easier, and is a syntax format that you define yourself. Keep in mind, however, that all popular template-Introduction solutions follow the same set of core implementation principles that, like programming languages, learning one language makes it easier to master other languages. The main reason to use the template engine is to separate the work of the front-end engineer and the back-end engineer, so the template engine is not only used by the backend engineer, but also by the front-end engineers

1. Back-end engineer's use of the template engine

In the PHP script, include the file where the template engine class resides. As shown below:

Require ("mytpl.class.php");    Contains the template engine class, which is equivalent to the template engine installation

Creates an object of the template engine class and assigns values to some member properties. As shown below:

$tpl=new MyTpl(); //创建模板引擎类的对象,也可以根据参数对成员初始化

Use the Assign () method in the template engine object to assign Dynamic data (including scalar and array types of data, such as arrays of data from a table in a database) to a template file, which can be used multiple times to assign any number of variables to a template. As shown below:

$tpl->assign ("var", "This is a value"); Scalar type data can be assigned using multiple $tpl->assign ("arr", Array (array), Array ("A", "B")); You can also assign arrays including multidimensional arrays

In a PHP script, by invoking the display () method in the template object and passing the template file name as a parameter, the corresponding template file in the specified directory is loaded into the PHP script. The custom syntax in the template is parsed by the substitution method in the template engine, and then the processed template is exported. As shown below:

$tpl->display ("Test.tpl");    The parameter "TEST.TPL" is a template file under a specific directory

2, the front-end engineer to use the template engine

The front-end engineer needs to store the authored template file in the specified directory, which is specified by using the $template_dir property in the Template object, and the default setting is the "templates" directory under the current directory. In addition, the name of the template file and the suffix of the settings can be arbitrary, such as INDEX.TPL, test.htm, HEADER.TP;

Template files are pure static negatives that are written by using the Web foreground language such as HTML, CSS, and JavaScript. However, you can define a variable (like a variable format in PHP) in the template file using the "<{" and "}>" two delimiters, which can accept and output the dynamic data that is allocated by the PHP script. The "<{" and "}>" two delimiter pairs used in the template can also be modified in the template engine class based on personal preference. As shown below:

Name: <{$name}>, Age: <{$age}>, Gender: <{$sex}>//templates use placeholders

If the array is assigned to a template in a PHP script, it can also be traversed in a template, and a multidimensional array can be traversed in a nested way. You use the "<{loop}>" tag pair defined in the template engine in a way that is similar to the syntax format of the foreach structure in PHP. As shown below:

<{loop $arr $value}>//traversing an element value in an array $arr element values     <{$value}>   //traverse the value in the output element each time <{/loop}>        // The end tag of the array is traversed in the template <{loop $arr $key + = $value}>   //Iterate through the element keys in the array $arr elements and element values <{$key}>    // Each time you iterate through the element values in the subscript array in the output element <{$value}>   //Iterate through the values in the output element <{/loop}>        //Iterate over the end tag of the array in the template <{loop $arr $value} >     //Traversal of element values in array $arr <{loop $arr $data}>    //using nested tags  to traverse element values in a two-dimensional array <{$value}>  // Each traversal of the value in the output element <{/loop}>       //traversing the inner end tag of an array in a template <{/loop}>        //traversing the outer end tag of an array in a template

The template engine can also parse branch structures written in template files using special tags, which are similar to the branching structure of PHP. is to implement the selection structure by using the "<{if}>" tag pair in the template file, or you can implement the selection structure of the multi-branch and nested branches. As shown below:

<{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 the word "20px" size </p> <{/if}><{/if}>

In the custom template engine, you also added the ability to include other template files in the template file. You can include a child template in the current template by using the <{include child template file name '}> ' tag, and also support the inclusion of another child template in the child template. As shown below:

<{include ' Other.tpl '}>

Using sample Analysis

You can separate the front-end language from the code in the backend language by loading the template engine in your program. First, in the PHP program to get the data stored in the database, and then by loading the template engine to allocate data, and then the template file through the template engine loaded and processed after the output. So the PHP program just creates the dynamic data, loads the template engine and assigns the dynamic data to the template, and completes the PHP program's work. and the template of the juice is only required to complete the front-end engineers, using HTML, CSS and JavaScript, such as the front page design language written. In addition, in the template file you need to use tags that the template engine can parse, and the dynamic data that is allocated in PHP is referenced in the template.

1, the design of the database

Assuming that the database server is on the "localhost" host, the user name and password for the connection are "admin" and "123456" respectively, a database named "MyDB" is created on the server, and a user table named "User" is created in the database. The SQL Inquiry statement that created the table looks like this:

CREATE TABLE User (ID SMALLINT (3) NOT NULL auto_increment, name VARCHAR (TEN) NOT null DEFAULT "', Sex VARCHAR (4) NOT NULL D Efault ', Age SMALLINT (2) is not null default ' 0 ', email VARCHAR (NO) null default ' ', PRIMARY KEY (id));

After the user table is created, you can then insert some data into the table to use as a sample demonstration, and the SQL query statement looks like this:

INSERT into User (name,sex,age,email) VALUES ("A", "male", "a@a.com"), ("B", "female", "b@b.com"), ("C", "female", "a", "c@c.com"), ( "D", "female", 24,d@d.com);

2, the design of the template

The design of the template does not appear any PHP code, can be done by the front-end personnel. In the custom template engine, you specify that you want to go to the specified directory to find the template file, this particular directory can be specified when creating template engine objects, or you can use the default directory settings, by default the template file can be stored in the current directory in the "Templates" directory. This example requires a total of three template files Main.tpl, Header.tpl, and FOOTER.TPL, which are stored in this default directory setting. The code for these three template files is as follows:

Header file for template Header.tpl

<! DOCTYPE html>

End of template file Footer.tpl

  <p style= "width:200px;margin:0 auto;" >##### <{$author}> #####</p>   </body>

Main template file Main.tpl

<{include ' Header.tpl '}> <table border= "1" align= "center" width= ">  <{loop $users $user}>   <tr>     <{loop $user $u}>      <{if $u = = "Male"}>       <td style= "Color:green" >      <{ ElseIf $u = = "female"}>       <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 which the <{include "Header.tpl"}> and <{include "FOOTER.TPL"}> two tags are used in the file, respectively, at the top and bottom of the file, Separate header and trailer template files are included in the main template file. and use the <{tableName}> tag in this file to get the name of the table dynamically allocated from PHP, and to use double <{loop}> tag nesting, traverse the $users of the two-dimensional array obtained in the database dynamically allocated from PHP, and The <{loop}> tags use conditions to select tags <{if}> combinations to set the table background of the data in which gender is "male" to red and some other judgments. Included header template file Header.tpl and trailer template file Footer.tpl can also get data that is dynamically assigned to a template from PHP

3. PHP Program Design

With the use of the template engine, PHP programmers in writing code, only need PHP a language, no longer to use HTML, CSS and JavaScript and other page design language to complete the front-end work. The following is a PHP script file named index.php, and the template engine class is located in the same directory as the file mytpl_class.php. The code looks like this:

<?php//Includes template engine class include "mytpl.class.php"; Create template Engine Object $TPL = new Mytpl; Connect database $pdo = new PDO ("Mysql:host=localhost;dbname=mydb", "admin", "123456"); Execute SQL statement $stmt = $PDO-Prepare ("Select ID, Name, sex,age,email from the User Order by id"); $stmt->execute (); $data = Fetchall (PDO::FETCH_ASSOC), $stmt; This is the dynamic data obtained from the database and needs to be displayed in the template $tpl->assign (' title ', ' Custom Template engine '), $tpl->assign (' Auto ', "small Match"); $tpl->assign (' users ', $data); $TPL display ("Main.tpl");? >

In the above php script file, connect the MySQL server through the PDO object, and get all the records in user table users, and save the data in the variable form of PHP's two-dimensional array variable. The object data of the template engine class is then created and initialized using the "mytplclss.php" file that is included in the current directory. The object TPL of the template engine class is created and initialized using the "mytplclss.php" file that is included in the current directory. The Assign () method in the object then assigns some data to the template and then uses the display () method in that object to load the template file MAIN.TPL. The special variables marked in the template are replaced with the dynamic Data assigned from PHP, and the template page is output after processing is finished. The output of the page is as follows

Limited to a variety of constraints, such as time, experience, to make a custom PHP template engine is very difficult. In fact, the need is not to re-construct a php template, but choose a most close to their own PHP template to be modified

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.