Template technology in PHP has always been a popular technology. Since 2001, many fans in PHP quoted the MVC development model in PHP, template technology is more hot.
Many famous template engines, such as phplib Template, FastTemplate, EasyTPL, BTemplate, and SMARTY template engines that are now packed in PHP.NET and many fans.
I personally like those short-sighted PHP code, like the template engine implemented by SMARTY's 2000-multi-line code, have to be a daunting.
For a few more time, I saw a article on phpe.net called << Beyond Template Engine >> The author Brian Lozier said that it is really very reasonable. He said this: Smarty's goal is to "separate business logic from the performance" rather than "Separation of PHP code and HTML code". But Smarty is really too big. If I am using Smarty, I will feel that Smarty will affect PHP code execution efficiency, first in parsing the SMARTY code that parsed more than 2,000 lines may have a large latency. Although he uses compilation technology, the program still needs to run the smarty engine include at runtime, and the PHP script engine will go to parse this huge code. Think about it is also terrible.
Affected by Brian Lozier, I realized that PHP itself is an embedded scripting language. If we can use a template written with a simple PHP code, and directly in the runtime, isn't it more fast? The result is also the same as I guess. After I use Brian Lozier's class test, I really be 50% faster than Smarty. Tag code my name is {myname}. Why don't we write to my name is = $ MyName?>. Is this like? And there are common lists in template, in fact, simple loops. Begin user_list -> user ID: {var0} User name: {var1} Why don't we write as follows?
php foreach {?> user ID: = ['id']?> user name: = ['name']?> php}?>
As early as a year, I tried to use this method to do some businesses and governments, but I didn't consider the benefits of doing this. Just feeling this template I don't need a separate code to deal with him, just simple include include. Moreover, I remember that when I did these templates directly written directly in PHP language, I was very fast, so that I have developed several artificials, I have developed a lot of interest in PHP, and I started learning PHP. Script language.
Recently, I have been influenced by the << Beyond Template Engine >>, so I decided to implement a template processing class according to his thoughts. After two or three days, I have completed a template. class. Now posted here so that you can discuss with me.
Considering that this tag that is often used often uses {name} to do templates, so I write a simple compile () method to parse such a file, convert it to = $ Name?> Such php Template file. The converted file is then stored in the corresponding cache directory and then provides a _parse () method to the include file and then output in the main program. In order to simplify the calling method. Use a PARSE () method to call the above two private methods. The following is an example:
First give a directory structure: / root directory ├ --cache stores PHP template cache file ├─includes class inventory Putalog │ └─Template Template Processing Template.php Class Library File Save Directory └─Templates Template Directory ├─Imgs Template file Picture Directory │ └ -VER.1 └ -TPLS Template file directory └ -VER.1 Example 1: Process for the template file for the HTML type. Example 1: Process for the template file for the HTML type. Test.htm.php template file Store in /Templates/tpls/ver.1/ directory
{title} title> head>
- Trim PHP code That Can't Occur in Html Type Template File. Now, That Will Be Disable. -> = $ test?> IF ($ a == $ b) echo 'a == b';?>
$ condition is true td> tr> table>
$ a == $ b td> tr> table> < ! - Endif ->
$ a! = $ B td> tr> table> < ! - Endif ->
id td>
name td> tr>
{user [id]} td>
{user [name]} td> tr> TABLE> body>
html> Test_htm.php file For class library calls, this file is stored in / directory below is a specific process of modifying such an HTML type template.
Require_once ('Include / Template / Template.php'); $ TPL = New Template; $ TPL-> SetFile ('Templates / TPLS / Ver.1 / Test.htm.php', TPL_HTM); // For HTM Type Template, through this setting, compiled template file $ TPL-> setCachedir ('cache /'); $ TPL-> setvar ('Title'); $ TPL-> Setvar ('Condition ', True); $ TPL-> setvar (' a ',' a '); $ TPL-> setvar (' b ',' a '); $ user_list = array (array (' id '=>' 1 ' , 'Name' => 'stangly.Wrong'), array ('id' => '2', 'name' => 'jear'),); $ TPL-> setvar ('user_list', $ user_list); Echo $ TPL-> PARSE ();?>
Observe changes in the directory structure
/
├ --cache
│ └─Templates
│ └ -TPLS
│ └ -VER.1
├ -includes
│ └─Template
└ --Templates
├─Imgs
│ └ -VER.1
└ -TPLS
└ -VER.1
The program will automatically in the cache directory, establish the same directory path as the path to the Template file to store the compiled template file. This personal feeling is very easy to find and tap. Example 2: For the processing of the Template file for the PHP type, observe what is different from the HTM type template file? Is it a form of all {title} to be replaced with = $ Title?> This form, and for The so-called Block is also replaced with the foreach () method.
Test.php.php template file is stored in the /Templates/tpls/ver.1/ directory
= $ title?> title> head> if ($ condition) {?>
$ condition is true! td> tr> table> }?> IF ($ A == $ b) {?>
$ a == $ b td> tr> table> }?> IF ($ A! = $ b) {?>
$ a! = $ b td> tr> table> }?>
ID td>
Name td> tr> foreach ($ user_list as $ user) {?>
= $ user [id]?> td>
= $ user [name]?> td> tr> }?> table> body> html> test_htm.php Document pairing the class library called example, this file is stored in / directory below is the specific process of making modifications for such an HTML type template.
Require_once ('Include / Template / Template.php'); $ TPL = New Template; $ TPL-> SetFile ('Templates / TPLS / VER.1 / TEST.PHP.PHP', TPL_PHP); // For PHP For the document, this setting is invalid / $ TPL-> setcachedir ('cache /'); // $ TPL-> setvar ('Title', 'I love jear'); $ TPL-> setvar ('Condition ", True); $ TPL-> setvar ('a', 'a'); $ TPL-> Setvar ('b', 'a'); $ users_list = array (array ('id' => '1', ' Name '=>' Stangly.Wrong '), array (' id '=>' 2 ',' name '=>' jear '),); $ tpl-> setvar (' user_list ', $ users_list); echo $ TPL-> PARSE ();?> The above is the template class call example, and the format of the template file content.
Finally, give the template.php file, where he is stored in / incrudes / template / directory.
// ------------------------------------------------------------------------------------------------------------------------- --------- // filename: Template.inc.php // Created: 2004-11-11 13:46 // Author: Stangly WRONG // Version: 2.1.4 // Description: Parse Template / / Modified: 2004-11-29 14:12 / / ------------------------------------------------------------------------------------------------------------------------------------------- ------------------ Define ('TPL_PHP', 'PHP'); Define ('TPL_HTM', 'HTM'); Define ('TPL_CACHE_DIR', './cache / '); class templateEngine {var $ _TPLDIR; var $ _file = null; var $ _VAR = array (); var $ _ERR = false; var $ _ERR = false; var $ _ERROR_CENTER; function templateEngine () {if (! Class_exists (' errorcenter ') | | Is_A ($ global ") DIE ('can not initialize errorcenter!'); Else $ this -> _ error_center = & $ globals ['error_center']; return;} function _parse $ Filename = '') {$ sourcefile = ($ filename == ')? $ This -> _ tpldir. $ This -> _ file: $ filename; if (! File_exists ($ sourcefile)) $ this -> _ error_center-> appenderror ('TPL_1', 'Template File Was Not Found!'); @extract ($ this -> _ var); ob_start (); include ($ sourcefile); $ contents = & ob_get_contents (); OB_END_CLEAN (); return $ contents;} function _setfile ($ this -> _ file = baseName ($ filename); $ this -> _ tpldir = dirname ($ filename). '/';} Function setvar ($ Name) $ VAR = '') {IF (is_ARRAY ($ name)) Foreach ($ NAME AS $ K =>
$ v) $ this -> _ var [$ k] = $ V; Else $ this -> _ var [$ name] = $ var;} function clearvar () {unset ($ this -> _ var);}} class template extends TemplateEngine {var $ _CacheDir = TPL_CACHE_DIR; var $ _CompiledExt = '.php'; var $ _CompilePre = '_c_co_'; var $ _TplType = TPL_PHP; var $ _MultiCacheDir = TRUE; var $ _left_d = '/ {'; var $ _right_d = '/}'; Var $ _compile_p = array (0 => '//) (.*) //', 1 => '// {([^ /} / S / R / N / ;] ) /} / ', 2 =>' // {/ s * list ([A-ZA-Z0-9 _ / [/] / '] ) / S AS / S ([A-ZA- Z0-9 _ / [/] / '] ) / s * /} /', 3 => '// {/ s * endlist / s * /} /', 4 => '// {/ s * List / s ([A-ZA-Z0-9 _] ) / S AS / S ([A-ZA-Z0-9 _ / [/] / '] ) / s => / s ([A-ZA- Z0-9 _ / [/] / '] ) / s * /} /', 5 => '// {/ s * IF / s ([A-ZA-Z0-9 _ / [/] /'] ) / s * /} / ', 6 =>' // {/ s * Endif / s * /} / ', 7 =>' // {/ S * IF / s ([A-ZA-Z0-9_ / [/] / '] ) / s (== |! = | <|> | <= |> =) / s ([A-ZA-Z0-9 _ / [/] /'] ) / s * /} / ', 8 =>' // {/ s * else / s * /} / ',); Var $ _Compile_S = array (0 => ', 1 =>' PHP ECHO / $ / 1;?> ', 2 =>' php foreach (/ $ / 1 as / $ / 2) {?> ', 3 =>' Php}?> ', 4 => Php foreach (/ $ = 1 as / $ / 2 => / $ / 3) {?> '
, 5 => Php if (/ $ / 1) {?> ', 6 => Php}?>', 7 => PHP IF (/ $ / 1/2 / $ / 3) {?> ', 8 =>' Php} else {?> ',); Function template () {templateEngine :: templateEngine ();} function _GenerateCompileDFileName ($ filename =') {$ _RETURN = ( $ Filename == '')? $ This -> _ file: $ filename; if ($ this -> _ multicachedir) {$ _TEMP = @preg_replace ('/ ^ (//// - | /. {2} //) / ',' ', $ this -> _ TPLDIR); Return $ this -> _ Cachedir. $ _ Temp. $ this -> _ compilepre. $ _ return; $ this -> _ compilext;} else return $ this-> _ cachedir. $ this-> _CompilePre. $ _ RETURN. $ This -> _ compiledext;} function _mkdir ($ dir, $ dirmode = 700) {$ dir = dirname ($ dir); if (! Empty ($ dir)) {if (! File_exists ($ DIR) )) {PREG_MATCH_ALL ('/ (^ //] *) //? / I', $ dir, $ atmp); $ base = ""; foreach ($ atmp [0] AS $ key = > $ VAL) {$ base = $ base. $ val; if (! File_exists ($ base)) {echo "error: cannot". $ base; return -1 }}} Else if (! Is_dir ($ dir)) {echo "error:". $ Dir. "Exists and is not a directory"; Return -2;
}}}}} Function _compile ($ filename = ') {$ sourcefile = ($ filename ==')? $ This -> _ tpldir. $ This -> _ file: $ filename; $ targetfile = $ this-> _GenerateCompiledFileName ($ FileName); if (! is_dir ($ this -> _ TplDir)) $ this -> _ error_center-> AppendError ( 'tpl_3', 'Cache dir did not to establish!'); if (file_exists ($ SourceFile)! $ This -> _ error_center-> appenderror ('TPL_2', 'Cannot Compile Template File, Because Template File Was Not Found!'); $ Fp = fopen ($ sourcefile, 'RB'); $ content = @fread ($ FP, FileSize); Fclose ($ fp); $ Content = & preg_replace ($ this -> _ compile_p, $ this -> _ compile_s, & $ content); $ this -> _ mkdir ($ targetfile, '0777') $ Fp = fopen ($ TARGETFILE, 'WB'); FWRITE ($ FP, $ Content); fclose ($ fp);} function _isexpired () {$ sourcefile = $ this -> _ tpldir. $ This -> _ file; $ TargetFile = $ THIS -> _ generatec ompiledFileName (); $ SourceModTime = @filemtime ($ SourceFile); $ TargetModTime = @filemtime ($ TargetFile); if ($ SourceModTime <$ TargetModTime) return FALSE; else return TRUE;} function _ParseHtml () {if ($ this- > _ISEXPIRED ()) $ this -> _ compile (); return @ $ this -> _ parse ($ this -> _ generateCompiledFilename ($ filename));} Function setchedir ($ cachedir) {$ this -> _ cachedir = $ cachedir;