晒一下我的模板引擎,欢迎拍砖
本帖最后由 xuzuning 于 2012-05-23 15:02:49 编辑
别不多说,直接上代码
template.php(3.55K)
<?php <br />
class template {<br>
protected $data = array();<br>
protected $drillmode = 0;<br>
function __construct($s) {<br>
if(file_exists($s)) $s = file_get_contents($s);<br>
$this->find_var($s);<br>
$this->data = explode('
$this->data[0] = '<?php $_st=$_var=array();?>';<br>
$this->find_dsn();<br>
}<br>
//新增 run 方法,<br>
function run() {<br>
//include "data://," . join('data);<br>
eval('?>' . join('data));<br>
}<br>
function find($pattern) {<br>
$this->pattern = $pattern;<br>
return array_filter($this->data, array($this, 'find_callback'));<br>
}<br>
private function find_dsn() {<br>
foreach($this->find("#\bdsn\b#i") as $k=>$v) {<br>
$t = $this->find_tag($tag = strtok($v, ' '), $k);<br>
end($t);<br>
$dsn[] = array( $k, key($t) );<br>
}<br>
if($this->drillmode) {<br>
foreach($this->find("#\bdrill\b#i") as $k=>$t) {<br>
foreach($dsn as $i=>$v) if($k $v[0]) $t = $i;<br>
$drill[] = $dsn[$t];<br>
unset($dsn[$t]);<br>
}<br>
}<br>
foreach($dsn as $v) {<br>
list($start, $end) = $v;<br>
preg_match('/\bdsn\s*=\s*([^\s>]+)/i', $this->data[$start], $reg);<br>
$this->data[$start] = str_replace(' '.$reg[0], '', $this->data[$start]);<br>
<br>
$m = explode(',', trim($reg[1], '\'"')) + array(0, 0, '');<br>
$code_start = "?php if(isset(\$_var))\$_st[]=\$_var;foreach((isset(\$_var['$m[0]'])?\$_var['$m[0]']:\$this->$m[0]('$m[1]','$m[2]')) as \$_key=>\$_var){?>";<br>
$code_end = "?php }\$_var=array_pop(\$_st);?>";<br>
switch($m[1]) {<br>
case 0:<br>
$t = explode('>', $this->data[$start]);<br>
$t[1] = "
$this->data[$start] = join('>', $t);<br>
$this->data[$end] = "$code_enddata[$end];<br>
break;<br>
case 1:<br>
$this->data[$end] .= "
$this->data[$start] = "$code_startdata[$start];<br>
break;<br>
default:<br>
$n = round(100/$m[1]);<br>
$this->data[$end] .= "
$this->data[$start] = "$code_start
登录后复制
data[$start];
break;
}
}
if($this->drillmode) foreach($drill as $v) {
list($start, $end) = $v;
preg_match('/\bdsn\s*=\s*([^\s>]+)/i', $this->data[$start], $reg);
$this->data[$start] = str_replace(' '.$reg[0], '', $this->data[$start]);
$m = explode(',', trim($reg[1], '\'"')) + array(0, 0, '');
$code = '';
for($i=$start; $i
$code .= 'data[$i];
if($i > $start) unset($this->data[$i]);
}
$code = addslashes($code);