Home > Article > Backend Development > PHP understands the implementation principle by writing a template class yourself
I believe many PHPers have come into contact with templates. How are templates implemented with their specific parsing syntax? This article lets everyone clearly understand the principle of templates by writing a simple template parsing class.
miniClass
class mini { public $template_dir = ''; // 模板文件存放的位置 public $compile_dir = ''; // 模板文件编译后存放的位置 public $array = array (); public function assign($key, $value) { $this->array [$key] = $value; } /* * 调动compile来编译模板,并自动引入; */ public function display($template) { $comp = $this->compile ( $template ); include ($comp); } /* * 传一个参数,读取那个html模板 流程:把模板读取过来,编译成php */ public function compile($template) { // $template是一个html文件 $temp = $this->template_dir . '/' . $template; $source = file_get_contents ( $temp ); // 再把编译后的内容保存成.php文件 $comp = $this->compile_dir . '/' . $template . '.php'; // 判断模板是否已经存在,或者修改; if (file_exists ( $comp ) && filemtime ( $temp ) < filemtime ( $comp )) { return $comp; } $source = str_replace ( '{$', '<?php echo $this->array[\'', $source ); $source = str_replace ( '}', '\'];?>', $source ); // echo $source; file_put_contents ( $comp, $source ); return $comp; } }
Related recommendations:
##[Course] PHP underlying analysis video tutorial
The above is the detailed content of PHP understands the implementation principle by writing a template class yourself. For more information, please follow other related articles on the PHP Chinese website!