[thinkphp] 是如何输出一个页面的

表面上看,TP输出一个页面很简单:$this->display();

实际上是怎么回事呢?$this->display(); 这个display()方法是定义在ThinkPHP/Library/Think/Controller.class.php这个文件中的

protected function display($templateFile='',$charset='',$contentType='',$content='',$prefix='') {
    $this->view->display($templateFile,$charset,$contentType,$content,$prefix);
}

而这个display方法其实是属于$this->view这个对象的。$this->view 是什么呢?还是ThinkPHP/Library/Think/Controller.class.php这个文件

    public function __construct() {
        Hook::listen('action_begin',$this->config);
        //实例化视图类
        $this->view     = Think::instance('ThinkView');
        //控制器初始化
        if(method_exists($this,'_initialize'))
            $this->_initialize();
    }

可以看到$this->view其实是ThinkView类的一个实例,ThinkView 就是ThinkPHP/Library/Think/View.class.php啦

那我们就去看看View.class.php中的display方法是长什么样的

    public function display($templateFile='',$charset='',$contentType='',$content='',$prefix='') {
        G('viewStartTime');
        // 视图开始标签
        Hook::listen('view_begin',$templateFile);
        // 解析并获取模板内容
        $content = $this->fetch($templateFile,$content,$prefix);
        // 输出模板内容
        $this->render($content,$charset,$contentType);
        // 视图结束标签
        Hook::listen('view_end');
    }

忽略G方法、钩子, 就是简单的两部分内容:1、解析并获取模板内容;2、输出模板内容;

具体怎么回事呢?

第一点是有两部分的,首先获取模板文件的位置($this->parseTemplate) ,然后把里面的PHP标签替换成具体的内容 

第二点呢,太简单了,直接echo $content,就输出内容了

到此,$this->display()背后的过程就清清楚楚了。

原文地址:https://www.cnblogs.com/bushe/p/4620378.html