Simple custom php template engine and php template engine

Source: Internet
Author: User
Tags php foreach php template vars

Simple custom php template engine and php template engine

The idea of the template engine is derived from the MVC (Model View Controller) Model, that is, the Model layer, View layer, and Controller layer.

On the Web end, the model layer is the database operation; the view layer is the template, that is, the Web Front-end; the Controller is the various PHP operations on data and requests. The template engine separates the view layer from other layers so that php code and html code are not mixed together. When php code and html code are mixed together, the readability of the code will be deteriorated, and it will become very difficult to maintain the code later.

Most template engines have similar principles. The core is to use regular expressions to parse the template and compile the specified identification statement into a php statement. Then, you only need to include the compiled file when calling the template, in this case, php and html statements are separated. You can even further output the php output to the buffer, and then compile the Template into a static html file. In this way, the static html file is opened directly during the request, which greatly speeds up the request.

The simple custom template engine has two classes: the first is the template class and the second is the compilation class.

The first is the compilation class:

Class CompileClass {private $ template; // private $ content of the file to be compiled; // The text to be replaced is private $ compile_file; // The compiled file is private $ left = '{'; // left delimiter private $ right = '}'; // right delimiter private $ include_file = array (); // private $ config; // template configuration file private $ T_P = array (); // The expression to be replaced private $ T_R = array (); // The replaced string public function _ construct ($ template, $ compile_file, $ config) {} public function compile () {$ this-> c_include (); $ this-> c_var (); $ this-> c_staticFile (); file_put_contents ($ this-> compile_file, $ this-> content );} // process include public function c_include () {}// process various assignments and basic statements public function c_var () {}// parse static JavaScript public function c_staticFile () {}}

The general structure of the compilation class is as above. The job of the compilation class is to parse the prepared Template File Based on the configuration file, replace it with the rule, and output it to the file. The content of this file is a mixture of php and html, but you do not need to care about this file when using the template engine for development, because we want to write a template file, that is, an html file and a custom tag file. In this way, the View and the other two layers are separated.

In this custom template engine, the left and right delimiters are braces, and the specific parsing rules are placed in _ construct ().

// The regular expression $ this-> T_P [] = "/$ this-> left \ s * \ $ ([a-zA-Z _ \ x7f -\ xff] [a-zA-Z0-9 _ \ xf7-\ xff] *) \ s * $ this-> right/"; $ this-> T_P [] ="/$ this-> left \ s * (loop | foreach) \ s * \ $ ([a-zA-Z _ \ x7f-\ xff] [a-zA-Z0-9 _ \ xf7-\ xff] *) \ s * $ this-> right/"; $ this-> T_P [] ="/$ this-> left \ s * (loop | foreach) \ s * \ $ ([a-zA-Z _ \ x7f-\ xff] [a-zA-Z0-9 _ \ xf7-\ xff] *) \ s + ". "as \ s + \ $ ([a-zA-Z _ \ x7f-\ xff] [a-zA-Z0-9 _ \ xf7-\ xff] *) $ this-> right/"; $ this-> T_P [] = "/ $ This-> left \ s * \/(loop | foreach | if) \ s * $ this-> right /"; $ this-> T_P [] = "/$ this-> left \ s * if (. *?) \ S * $ this-> right/"; $ this-> T_P [] ="/$ this-> left \ s * (else if | elseif )(.*?) \ S * $ this-> right /"; $ this-> T_P [] = "/$ this-> left \ s * else \ s * $ this-> right /"; $ this-> T_P [] = "/$ this-> left \ s * ([a-zA-Z _ \ x7f-\ xff] [a-zA-Z0-9 _ \ xf7-\ xff] *) \ s * $ this-> right/"; // The replaced string $ this-> T_R [] =" <? Php echo \ $ \ 1;?> "; $ This-> T_R [] =" <? Php foreach (array) \\ 2 as \ $ K =>\$ V) {?> "; $ This-> T_R [] =" <? Php foreach (array) \$ \\ 2 as \\ 3) {?> "; $ This-> T_R [] =" <? Php }?> "; $ This-> T_R [] =" <? Php if (\ 1) {?> "; $ This-> T_R [] =" <? Php} elseif (\ 2) {?> "; $ This-> T_R [] =" <? Php} else {?> "; $ This-> T_R [] =" <? Php echo \ $ \ 1;?> ";

The above parsing rules include basic output and some common syntaxes, such as if and foreach. Use the preg_replace function to replace the template file. The details are as follows:

<! -- Template file --> {$ data} {foreach $ vars} {if $ V = 1} <input value = "{V}" >{ elseif $ V = 2} <input value = "123123" >{ else} <input value = "sdfsas is aa" >{/ if }{/ foreach }{ loop $ vars as $ var} <input value = "{var}"> {/loop} // after parsing <? Php echo $ data;?> <? Php foreach (array) $ vars as $ K => $ V) {?> <? Php if ($ V = 1) {?> <Input value = "<? Php echo $ V;?> "> <? Php} elseif ($ V = 2) {?> <Input value = "123123"> <? Php} else {?> <Input value = "sdfsas is aa"> <? Php }?> <? Php }?> <? Php foreach (array) $ vars as & $ var) {?> <Input value = "<? Php echo $ var;?> "> <? Php }?>

The compilation class is basically like this, and the rest of the include and JavaScript parsing are similar.

Then there is the template class.

Class Template {// configure the array private $ _ arrayConfig = array ('root' => '', // file root directory 'suffix '=> '.html ', // The template file suffix 'template _ dir' => 'templates', // The folder where the template is located 'compile _ dir' => 'templates _ C ', // The compiled folder 'cache _ dir' => 'cache', // The static html address 'cache _ htm' => false, // whether to compile the static html file 'suffix _ cache' => '.htm', // set the suffix of the compiled file 'cache _ time' => 7200, // automatic update interval 'php _ call' => true, // whether native php code 'debug' => 'false' is supported ',); private $ _ value = array (); private $ _ compileTool; // compiler static private $ _ instance = null; public $ file; // template file name public $ debug = array (); // debug information public function _ construct ($ array_config = array ()) {}// set the configuration file public function setConfig ($ key, $ value = null) {}// inject a single variable public function assign ($ key, $ value) {}// inject the array variable public function assignArray ($ array) {}// whether to enable the cache public function needCache () {}// if you need to re-compile the file public function reCache () {}// display template public function show ($ file ){}}

The workflow of the entire template class is to first instantiate the template class object, then assign values to the variables in the template using the assign and assignArray methods, and then call the show method, import the template and configuration file into the instantiated object of the compilation class and then include the compiled php and html mixed files directly to display the output. The simple process is like this. The detailed code is as follows:

Public function show ($ file) {$ this-> file = $ file; if (! Is_file ($ this-> path () {exit ("corresponding template file not found ");} $ compile_file = $ this-> _ arrayConfig ['compile _ dir']. md5 ($ file ). '. php '; $ cache_file = $ this-> _ arrayConfig ['cache _ dir']. md5 ($ file ). $ this-> _ arrayConfig ['suffix _ cache']; // if you need to re-compile the file if ($ this-> reCache ($ file) === false) {$ this-> _ compileTool = new CompileClass ($ this-> path (), $ compile_file, $ this-> _ arrayConfig); if ($ this-> needCache ()) {// output to the buffer ob_sta Rt () ;}// import the assigned variable to the current symbol table extract ($ this-> _ value, EXTR_OVERWRITE); if (! Is_file ($ compile_file) or filemtime ($ compile_file) <filemtime ($ this-> path ())) {$ this-> _ compileTool-> vars = $ this-> _ value; $ this-> _ compileTool-> compile (); include ($ compile_file );} else {include ($ compile_file);} // if You Need To compile it into a static file if ($ this-> needCache () === true) {$ message = ob_get_contents (); file_put_contents ($ cache_file, $ message) ;}} else {readfile ($ cache_file );}}

In the show method, I first determine the existence of the template file, and then use MD5 encoding to generate the file name of the compiled and cached files. Then, you can determine whether to compile the file based on whether the compiled file exists and whether the write time of the compiled file is earlier than the template file. To compile a PHP file, use the compilation class to compile the PHP file. Then you only need to include the compilation file.

To speed up template loading, You can output the compiled file to the buffer, that is, the ob_start () function. All the output will not be output to the browser, instead, it is output to the default buffer, which reads the Output Using ob_get_contents () and saves it as a static html file.

The specific usage is as follows:

require('Template.php');$config = array( 'debug' => true, 'cache_htm' => false, 'debug' => true);$tpl = new Template($config);$tpl->assign('data', microtime(true));$tpl->assign('vars', array(1,2,3));$tpl->assign('title', "hhhh");$tpl->show('test');
 

The cached files are as follows:

<! DOCTYPE html> 

A simple custom template engine is complete. Although simple, it can be used, and the focus is on the fun and gains of wheel building.
Complete code can be found at my github.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.