Created
March 2, 2018 19:33
-
-
Save qti3e/f32defb0ffcb90f7e4d8a02765995637 to your computer and use it in GitHub Desktop.
A simple template engine in PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// 2015/07 :) | |
/** | |
* The core class of Template Engine | |
* Class templateEngine | |
*/ | |
class templateEngine{ | |
/** | |
* @type array | |
*/ | |
private $values = array(); | |
/** | |
* Set template variable in server side | |
* @param $property | |
* @param $value | |
*/ | |
public function assign($property,$value){ | |
$this->values[$property] = $value; | |
} | |
public function display($file_name){ | |
$file = file_get_contents($file_name); | |
preg_match_all("/({(\s|\S)*?})/",$file,$commends); | |
$var = json_decode(json_encode($this->values)); | |
$var->_GET = $_GET; | |
$file = str_replace("'","\\'",$file); | |
foreach ($commends[0] as $commend) { | |
$original = $commend; | |
$commend = ltrim(rtrim($commend,"}"),"{"); | |
$arg = explode(" ",$commend); | |
$function = $arg[0]; | |
if($commend[0] === "$"){ | |
$args = $this->argCrater($commend); | |
$commend = str_replace([",,",","],[".\" \".","."],$args); | |
$file = str_replace($original,"'.".$commend.".'",$file); | |
} | |
if($function === "mod"){ | |
$commend = $arg[1]."%".$arg[2]; | |
$file = str_replace($original,"'.".$commend.".'",$file); | |
} | |
if($function === "set"){ | |
$n = str_replace(".","->",$arg[1]); | |
$var->$n = ltrim($commend,"set ".$arg[1]); | |
$file = str_replace($original,null,$file); | |
} | |
} | |
$file = "echo'".$file."';"; | |
eval($file); | |
} | |
private function argCrater($text){ | |
$args = explode(",",$text); | |
$i = 0; | |
foreach($args as $arg){ | |
if(@$arg[0] == "$"){ | |
$args[$i] =str_replace( | |
["$","."], | |
['$var->','->'], | |
$arg); | |
} | |
$i++; | |
} | |
$text = implode($args,','); | |
return $text; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment