Home  >  Article  >  Backend Development  >  PHP understands the implementation principle by writing a template class yourself

PHP understands the implementation principle by writing a template class yourself

*文
*文Original
2017-12-23 17:17:421241browse

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 ( &#39;{$&#39;, &#39;<?php echo $this->array[\&#39;&#39;, $source );
        $source = str_replace ( &#39;}&#39;, &#39;\&#39;];?>&#39;, $source );
        // echo $source;
        file_put_contents ( $comp, $source );
        return $comp;
    }
}

Related recommendations:

##[Course] PHP underlying analysis video tutorial

php quick start summary

php concise function summary

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn