PHP implements simple template engine function examples and php template engine examples

Source: Internet
Author: User
Tags function examples php foreach php template php web development reflector

PHP implements simple template engine function examples and php template engine examples

This example describes how PHP implements simple template engine functions. We will share this with you for your reference. The details are as follows:

The mvc design mode is widely used in php web development. The data transmitted by the controller to the view layer must be parsed by the template engine. Implement a simple template engine that only contains the if and foreach tags and parses the $ foo variable.

Compile the template class and compiler compilation class. The Code is as follows:

<? Phpnamespace foo \ base; use foo \ base \ Object; use foo \ base \ Compiler; /*****/class Template extends Object {private $ _ config = ['suffix '=> '. php ', // file suffix 'templatedir' => '.. /views/', // the folder in which the template is located 'compiledir' => '.. /runtime/cache/views/', // The Directory stored after compilation 'suffixcompile' => '. php ', // After compilation, the file suffix 'iscachehtml' => false, // whether to re-compile the file into a static html file 'isortphp' => true, // whether php syntax 'cachetime' => 0, // cache time, in seconds]; private $ _ f Ile; // private $ _ valueMap = []; // key-Value Pair private $ _ compiler; // compiler public function _ construct ($ compiler, $ config = []) {$ this-> _ compiler = $ compiler; $ this-> _ config = array_merge ($ this-> _ config, $ config );} /*** [assign storage controller assigned key value] * @ param [type] $ values [key-value pair set] * @ return [type] [description] */public function assign ($ values) {if (is_array ($ values) {$ this-> _ valueMap = $ values;} else {t Hrow new \ Exception ('the value assigned to the view by the controller must be an array! ');} Return $ this ;} /*** [show display view] * @ param [type] $ file [files with compilation cache] * @ return [type] [description] */public function show ($ file) {$ this-> _ file = $ file; if (! Is_file ($ this-> path () {throw new \ Exception ('template file'. $ file. 'does not exist! ');} $ CompileFile = $ this-> _ config ['compiledir']. md5 ($ file ). $ this-> _ config ['suffixcompile ']; $ cacheFile = $ this-> _ config ['compiledir']. md5 ($ file ). '.html '; // After compilation, the file does not exist or the cache time expires. Re-compile and regenerate the html static cache if (! Is_file ($ compileFile) | $ this-> isRecompile ($ compileFile) {$ this-> _ compiler-> compile ($ this-> path (), $ compileFile, $ this-> _ valueMap); $ this-> _ config ['iscachehtml '] = true; if ($ this-> isSupportPhp ()) {extract ($ this-> _ valueMap, EXTR_OVERWRITE); // import the variable from the array to the current symbol table} if ($ this-> isReCacheHtml ()) {ob_start (); ob_clean (); include ($ compileFile); file_put_contents ($ cacheFile, ob_get_contents (); ob_end_flush () ;}else {readfile ($ cacheFile );}} /*** [isRecompile determines whether to re-compile Based on the cache time] * @ param [type] $ compileFile [compiled file] * @ return boolean [description] */private function isRecompile ($ compileFile) {return time ()-filemtime ($ compileFile)> $ this-> _ config ['cachetime'];} /*** [Does isReCacheHtml need to re-cache static html files?] * @ return boolean [description] */private function isReCacheHtml () {return $ this-> _ config ['iscachehtml '];}/*** [Does isSupportPhp support php syntax?] * @ return boolean [description] */private function issuppphp php () {return $ this-> _ config ['isortphp'];} /*** [path: Obtain the template file path] * @ return [type] [description] */private function path () {return $ this-> _ config ['templatedir']. $ this-> _ file. $ this-> _ config ['suffix '];}
<? Phpnamespace foo \ base; use foo \ base \ Object;/*****/class Compiler extends Object {private $ _ content; private $ _ valueMap = []; private $ _ patten = ['# \ {\ $ ([a-zA-Z _ \ x7f-\ xff] [a-zA-Z0-9 _ \ x7f-\ xff] *) \} # ',' # \ {if (. *?) \}# ',' #\{ (Else if | elseif )(.*?) \}# ',' #\{ Else \}#', '# \ {foreach \ $ ([a-zA-Z _ \ x7f-\ xff] [a-zA-Z0-9 _ \ x7f-\ xff] *)} #', '# \ {\/(foreach | if)} #', '# \ {\ ^ (k | v) \} #',]; private $ _ translation = ["<? Php echo \ $ this-> _ valueMap ['\ 1'];?> ", '<? Php if (\ 1) {?> ',' <? Php} else if (\ 2) {?> ',' <? Php} else {?> ', "<? Php foreach (\ $ this-> _ valueMap ['\ 1'] as \ $ k =>\$ v) {?> ", '<? Php }?> ',' <? Php echo \ $ \ 1?> ']; /*** [Compile the template file with compile] * @ param [type] $ source [template file] * @ param [type] $ destFile [compiled file] * @ param [type] $ values [key-value pair] * @ return [type] [description] */public function compile ($ source, $ destFile, $ values) {$ this-> _ content = file_get_contents ($ source); $ this-> _ valueMap = $ values; if (strpos ($ this-> _ content, '{$ ')! = False) {$ this-> _ content = preg_replace ($ this-> _ patten, $ this-> _ translation, $ this-> _ content );} file_put_contents ($ destFile, $ this-> _ content );}}

Our controller can call the assign Method in the template to assign values. The show method is used to compile the template.

/*** [Render rendering template file] * @ param [type] $ file [file to be compiled] * @ param [type] $ values [key-value pair] * @ param array $ templateConfig [compile configuration] * @ return [type] [description] */protected function render ($ file, $ values, $ templateConfig = []) {$ di = Container: getInstance (); // dependency injection instantiated object $ di-> template = function () use ($ di, $ templateConfig) {$ di-> compiler = 'foo \ base \ Compiler '; $ compiler = $ di-> compiler; return new \ foo \ base \ Template ($ compiler, $ templateConfig) ;}; $ di-> template-> assign ($ values)-> show ($ file );}

The Container class is as follows:

<? Phpnamespace foo \ base; use foo \ base \ Object; class Container extends Object {private static $ _ instance; private $ s = []; public static $ instances = []; public static function getInstance () {if (! (Self: $ _ instance instanceof self) {self: $ _ instance = new self ();} return self ::$ _ instance ;} private function _ construct () {} private function _ clone () {} public function _ set ($ k, $ c) {$ this-> s [$ k] = $ c;} public function _ get ($ k) {return $ this-> build ($ this-> s [$ k]);}/*** Autowiring) ** @ param string $ className * @ return object * @ throws Exception */publi C function build ($ className) {// if it is a Closure function (closures) if ($ className instanceof \ Closure) {// execute the Closure function return $ className ($ this );} if (isset (self ::$ instances [$ className]) {return self ::$ instances [$ className];} /** @ var ReflectionClass $ reflector */$ reflector = new \ ReflectionClass ($ className); // check whether the class can be instantiated. Exclude abstract classes and object interface interfaces if (! $ Reflector-> isInstantiable () {throw new \ Exception ($ reflector. ': This class cannot be instantiated! ');}/** @ Var ReflectionMethod $ constructor obtains the class constructor */$ constructor = $ reflector-> getConstructor (); // if no constructor exists, directly instantiate and return if (is_null ($ constructor) {return new $ className;} // get the constructor parameter, return the parameter list through the ReflectionParameter array $ parameters = $ constructor-> getParameters (); // recursively parse the parameters of the constructor $ dependencies = $ this-> getDependencies ($ parameters ); // create a new instance of the class. The parameters are passed to the class constructor. $ Obj = $ reflector-> newInstanceArgs ($ dependencies); self: $ instances [$ className] = $ obj; return $ obj ;} /*** @ param array $ parameters * @ return array * @ throws Exception */public function getDependencies ($ parameters) {$ dependencies = []; /** @ var ReflectionParameter $ parameter */foreach ($ parameters as $ parameter) {/** @ var ReflectionClass $ dependency */$ dependency = $ parameter-> getClass (); if (is_null ($ dependency) {// is a variable. if there is a default value, set the default value $ dependencies [] = $ this-> resolveNonClass ($ parameter );} else {// is a class that recursively parses $ dependencies [] = $ this-> build ($ dependency-> name) ;}} return $ dependencies ;} /*** @ param ReflectionParameter $ parameter * @ return mixed * @ throws Exception */public function resolveNonClass ($ parameter) {// if there is a default value, return the default value if ($ parameter-> isdefavalueavailable () {return $ parameter-> getDefaultValue ();} throw new \ Exception ('I have no idea what to do here. ');}}

To access the attributes of an object in key-value pairs, you must implement the four methods of the ArrayAccess interface,

The Object base class code is as follows:

public function offsetExists($offset) {    return array_key_exists($offset, get_object_vars($this));}public function offsetUnset($key) {    if (array_key_exists($key, get_object_vars($this)) ) {      unset($this->{$key});    }}public function offsetSet($offset, $value) {    $this->{$offset} = $value;}public function offsetGet($var) {    return $this->$var;}

In a Controller, you can call the render method of the parent Controller.
Copy codeThe Code is as follows: $ this-> render ('test \ Index', ['name' => 'Tom ', 'age' => 20, 'Friend s' => ['jack', 'Rose '], ['cachetime' => 10]);

Compile the view template file 'test \ Index ':

<! DOCTYPE html> 

So far, a simple template compilation engine is ready.

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.