Customizing the PHP template engine

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

The idea of the template engine is derived from the MVC Model View controller, which is the model layer, the view layer, and the controller layer.

On the web side, the model layer is the operation of the database; the view layer is the template, which is the Web front-end; the controller is php's various operations on data and Requests. The template engine is designed to separate the view layer from the other layers, so that the PHP code and HTML code are not mixed together. Because when the PHP code and HTML code are mixed together, the readability of the code will be poor, and later maintenance of the code will become Difficult.

Most of the template engine principle is similar, the core is the use of regular expressions to parse the template, the Agreed-upon specific identity statements compiled into a PHP statement, and then call only need to include the compiled file, so that the PHP statement and HTML statements Separated. You can even further output the PHP output to a buffer, and then compile the template into a static HTML file, so the request is to open the static HTML file directly, the request is much faster.

A simple custom template engine is two classes, the first being a template class, and the second being a compiled class.

The first is the compile class:

Class Compileclass {    Private $template;      File to be compiled    private $content;       The text that needs to be replaced    private $compile _file;       The compiled file    private $left = ' {';       Left delimiter    Private $right = '} ';      Right delimiter    private $include _file = array ();        The documents introduced are    private $config;        The profile of the template    private $T _p = array ();     The expression that needs 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);    }        Processing include public    function C_include () {}        //handling Various assignments and basic statements public    function C_var () {}        // Parsing of static JavaScript public        function C_staticfile () {}}

The approximate structure of the compiled class is the above, the work of the compiler class is based on the configuration of the file, the written template file according to the rules, replace and then output to the File. The contents of this file are mixed with PHP and html, but it is not necessary to care about this file when developing with the template engine, because we are writing a template file, which is a file of HTML and a mix of our own defined Tags. This separates the view from the other two Layers.

In this custom template engine, my left and right delimiters are curly braces, and the specific parsing rules are placed in the __construct ()

Regular expression to replace $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/";//replacement string $this->t_r[] =" <?php Echo \$\\1;?> "; $this->t_r[] =" <?php foreach ((array) \$\\2 as \ $K =>\ $V) {?> "; $this->t_r[] =" <?php Forea CH ((array) \$\\2 as &\$\\3) {?> "; $this->t_r[] =" <?php}?> "; $this->t_r[] =" <?php if (\\1) {?> "; $this->t_r[] =" <?ph p} ElseIf (\\2) {?> "; $this->t_r[] =" <?php} else {?> "; $this->t_r[] =" <?php echo \$\\1;?> ";

The above parsing rules contain basic output and some common syntax, if, foreach, and so On. The template file can be replaced with the Preg_replace Function. The specific situation is 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}

<?php echo $data after parsing, ><?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 job of compiling the class is roughly the same, and the rest of the include and JavaScript parsing are similar.

Then there is the template class

Class Template {//config array private $_arrayconfig = array (' root ' = = ',//file root ' suffix ' = > '. html ',//template file suffix ' template_dir ' = ' templates ',//template folder ' Compile_dir ' + ' Templat Es_c ',//post-compilation folder ' cache_dir ' = ' cache ',//static HTML storage address ' cache_htm ' and False,//whether        Static HTML file ' Suffix_cache ' + '. htm ',//set The suffix of the compiled file ' cache_time ' = + 7200,//auto-update interval    ' Php_turn ' = true,//whether support native PHP code ' debug ' = ' false ',);          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 ()) {}//step Setting profile public function Setconfig ($key, $value =null) {}//inject Single variable public function assign ($key, $value) {}//inject array variable public function Assignarr Ay ($Array) {}//whether to turn on cache public Function Needcache () {}//if you need to recompile the file public function recache () {}/ /show template public Function show ($file) {}}

The workflow of the entire template class is to instantiate the template class object first, then use the Assign and Assignarray methods to assign values to the variables in the template, then call the show method, Pass the template and configuration file into the instantiated object of the compiled class, and then directly include the compiled php, HTML Mixed file, Display Output. The simple process is this, the detailed code is as follows


Public Function Show ($file) {$this->file = $file;    If (!is_file ($this->path ())) {exit ("cannot Find the corresponding template file"); } $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 recompile the file if ($this->recache ($file) = = = False) {$this->_compiletool = new Compileclass ($this->path (        ), $compile _file, $this->_arrayconfig);        If ($this->needcache ()) {//output to buffer Ob_start ();        }//the assigned variable is imported into the current symbol table extract ($this->_value, extr_overwrite); If (!is_file ($compile _file) or filemtime ($compile _file) < filemtime ($this->path ())) {$this->_compileto            Ol->vars = $this->_value;            $this->_compiletool->compile ();        Include ($compile _file);        } else {include ($compile _file); }//if you need to compile to a static file if ($THIS-&GT;NEEDCACHe () = = = True) {$message = ob_get_contents ();        File_put_contents ($cache _file, $message);    }} Else {readfile ($cache _file); }}


In the show method, I first determine that the template file exists and then use MD5 encoding to generate the file name of the compiled file and the cache File. Then it is to determine whether or not to compile, the basis is to see if the compilation file exists and compile the file is less than the time to write the template File. If you need to compile, compile with the compiled class to generate a PHP file. And then just need to include this compilation file just Fine.

In order to speed up the loading of the template, the compiled file can be output to the buffer, that is, the Ob_start () function, all the output will not be output to the browser, but output to the default buffer, in the use of ob_get_contents () to read out the output, Saved as a static HTML File.

The specific use 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 (n/a)); $tpl- >assign (' title ', ' hhhh '); $tpl->show (' test ');

The files after the cache are as follows

<! DOCTYPE html>

A simple custom template engine is done, albeit rudimentary but can be used, and the focus is on the fun and harvesting of wheels.

Full code visible to my GitHub


Welcome to my personal blog: www.czrzchao.com

Customizing the PHP template engine

Related Article

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.