Write a mini-version of the Smarty template engine, the principle of understanding the template engine is very good

Source: Internet
Author: User
Tags md5 php and php code php template smarty template

Some time ago watching the Smarty template engine tutorial of the Hanshunping blog, and then combining myself with the TPL template engine written by Li Tinghui in the second quarter of the development CMS system. Today to write a mini version of the Smarty engine, although I did not delve into the source of smarty, but the principle of the template engine, still have a deep understanding. If there is anything else that needs improvement, remember to bring it up.

One, what is the Smarty template engine:

Smarty is a template engine written in PHP and is one of the most famous PHP template engines in the industry today. It separates the logic code from the external content, provides an easy-to-manage and useful way to separate the PHP code that was originally mixed with HTML code. To put it simply, the goal is to make the PHP programmer separate from the front-end staff, so that programmers change the logic content of the program does not affect the front-end staff of the page design, the front-end staff to re-modify the page does not affect the program logic, which in the multi-person cooperation project is particularly important. (from Baidu Encyclopedia)

Your own understanding is:

First, it is advantageous to separate the front-end development from the background development work and facilitate the division of labor;

Second, its caching mechanism is helpful to speed up the access of website;

Thirdly, template tags can also be written at once, everywhere called, convenient and concise good;

Second, the following development of the mini-template engine bar

(1) First of all, the template engine has been done to give you a look, first use, and then develop

① Mini version Smarty template engine directory structure is as follows:

The source code has a very detailed description, please see below

① to develop a template engine, there are two main classes, the template engine entry class and the template parsing class, respectively.

A. Create the Minismarty directory first, then a new file named MiniSmarty.class.php

The code is as follows:

/** * Minismarty Template engine * @link http://www.cnblogs.com/isuhua/* @author Andy _suhua <weibo.com/suhua123> * @package M
    Inismarty * @version 0.0.0.1 */class Minismarty {//template file public $template _dir = ' templates ';
    Compile file public $compile _dir = ' Templates_c ';
    Cache file Public $cache _dir = ' cache ';
    Template variable Public $_tpl_var = Array ();
    
    Whether to turn on cache public $caching = false;
    Public Function __construct () {$this->checkdir (); }//Check whether the directory is built with private function Checkdir () {if (!is_dir ($this->template_dir)) {exit (' modulo The Board file directory templates does not exist.
        Please manually create '); } if (!is_dir ($this->compile_dir)) {exit (' compile file directory Templates_c does not exist. Please create it manually.
        '); } if (!is_dir ($this->cache_dir)) {exit (' cache file directory '. $this->cache_dir. ' does not exist. Please create it manually.
        '); }}//template variable injection method public function assign ($tpl _var, $var = null) {if (Isset ($tpl _var) &&!em
  Pty ($TPL _var)) {          $this->_tpl_var[$tpl _var] = $var;
        } else {exit (' template variable name not set well '); }}//File compilation public function display ($file) {//template file $tpl _file = $this->template_dir. '/
        '. $file; if (!file_exists ($tpl _file)) {exit (' ERROR: template file does not exist.
        '); }//Compile file $parse _file = $this->compile_dir. '/'. MD5 ($file). $file.
        
        PHP '; Only if the compiled file does not exist or if the template file has been modified//before recompiling the file if (!file_exists ($parse _file) | | | filemtime ($parse _file) < Filemtime (
            $TPL _file)) {include ' smarty_compile.class.php ';
            $compile = new Smarty_compile ($tpl _file);
        $compile->parse ($parse _file);  }//Open cache to load cache file, otherwise directly load compiled file if ($this->caching) {//cache file $cache _file = $this->cache_dir. '/'. MD5 ($file). $file.
            HTML '; Only if the cache file does not exist or the compiled file has been modified//regenerate the cache file if (!file_exists ($cache _file) | | | filemtIME ($cache _file) < Filemtime ($parse _file)) {//Introduce cache file include $parse _file;
                Cached content $content = Ob_get_clean (); Generate Cache file if (!file_put_contents ($cache _file, $content)) {exit ' cache file generation error.
                ');
        }}//loading cache files include $cache _file;
        } else {//load compilation file include $parse _file; }
    }
}

B. Then create a new Minismarty template engine parser class file: MiniSmarty_Compile.class.php

The code is as follows:

<?php/** * minismarty template engine * @link http://www.cnblogs.com/isuhua/* @author Andy _suhua <weibo.com/suhua123> * @
    
    Package Minismarty * @version 0.0.0.1 */class Minismarty_compile {//template content private $content = ';
    Constructor public Function __construct ($tpl _file) {$this->content = file_get_contents ($tpl _file); }//Parse ordinary variables such as {$name} into $this->_tpl_var[' name '] public function Parsevar () {$pattern = '/\{\$ ([\w\
        d]+) \}/'; if (Preg_match ($pattern, $this->content)) {$this->content = preg_replace ($pattern, ' <?php echo \ $thi
        s->_tpl_var["$"]?> ', $this->content); }}///Here you can customize other parsers ...//template compilation Public Function parse ($parse _file) {//Call the normal variable parser $t
        His->parsevar ();
            Other parsers can be called here ...//After compilation is complete, generate the compile file if (!file_put_contents ($parse _file, $this->content)) { Exit (' Compile file generation error.
        '); }}}?>

C. Finally, you must create several new directories, namely the template file directory templates, the compiled file directory Template_c, the cache file directory caches.

If you (ˇˍˇ) want to ~ one-time success, you must create these directories, indispensable. Otherwise you will get an error and then ask you to create it manually.

D. Try it out, write demo.php, and test your customized mini-Minismarty template engine.

The demo.php code is as follows:

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.