Output组件负责向浏览器发送最终输出,是ci框架中使用非常广泛的一个组件,在之前的几篇源码阅读中,也使用到了这个组件,例如:load->view() 在阅读输出组件源码的时候,我们主要关注以下几个问题:

  1. Output是如何输出页面的,在最终输出的之前做了哪些处理?
  2. 页面缓存是怎么实现的?

1.构造函数

    public function __construct()
    {
        $this->_zlib_oc = (bool) ini_get('zlib.output_compression');
        $this->_compress_output = (
            $this->_zlib_oc === FALSE
            && config_item('compress_output') === TRUE
            && extension_loaded('zlib')
        );

        isset(self::$func_overload) OR self::$func_overload = (extension_loaded('mbstring') && ini_get('mbstring.func_overload'));

        // Get mime types for later
        $this->mimes =& get_mimes();

        log_message('info', 'Output Class Initialized');
    }

这个构造函数中一共做了三件事:

  1. 判断是否可以压缩输出内容,这是为了在之后的输出缓存中决定是否压缩;
  2. mbstring是否可以重载,因为ci框架中对mbstring标准库的一些函数进行了重载,而输出组件中正好要使用重载的函数,详细了解可以查看’./system/core/compat/mbstring.php’文件;
  3. ci框架中定义了一个mimes列表,将mimes列表取出,为了之后设置请求头时使用;

从构造函数中我们可以看出,output在输出内容之前,会对要输出的内容进行压缩。

2.输出函数——_display()

    /**
     * Display Output
     *
     * Processes and sends finalized output data to the browser along
     * with any server headers and profile data. It also stops benchmark
     * timers so the page rendering speed and memory usage can be shown.
     *
     * Note: All "view" data is automatically put into $this->final_output
     *   by controller class.
     *
     * @uses    CI_Output::$final_output
     * @param   string  $output Output data override
     * @return  void
     */
    public function _display($output = '')
    {
        // Note:  We use load_class() because we can't use $CI =& get_instance()
        // since this function is sometimes called by the caching mechanism,
        // which happens before the CI super object is available.
        $BM =& load_class('Benchmark', 'core');
        $CFG =& load_class('Config', 'core');

        // Grab the super object if we can.
        if (class_exists('CI_Controller', FALSE))
        {
            $CI =& get_instance();
        }

        // --------------------------------------------------------------------

        // Set the output data
        if ($output === '')
        {
            $output =& $this->final_output;
        }

        // --------------------------------------------------------------------

        // Do we need to write a cache file? Only if the controller does not have its
        // own _output() method and we are not dealing with a cache file, which we
        // can determine by the existence of the $CI object above
        if ($this->cache_expiration > 0 && isset($CI) && ! method_exists($CI, '_output'))
        {
            $this->_write_cache($output);
        }

        // --------------------------------------------------------------------

        // Parse out the elapsed time and memory usage,
        // then swap the pseudo-variables with the data

        $elapsed = $BM->elapsed_time('total_execution_time_start', 'total_execution_time_end');

        if ($this->parse_exec_vars === TRUE)
        {
            $memory = round(memory_get_usage() / 1024 / 1024, 2).'MB';
            $output = str_replace(array('{elapsed_time}', '{memory_usage}'), array($elapsed, $memory), $output);
        }

        // --------------------------------------------------------------------

        // Is compression requested?
        if (isset($CI) // This means that we're not serving a cache file, if we were, it would already be compressed
            && $this->_compress_output === TRUE
            && isset($_SERVER['HTTP_ACCEPT_ENCODING']) && strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== FALSE)
        {
            ob_start('ob_gzhandler');
        }

        // --------------------------------------------------------------------

        // Are there any server headers to send?
        if (count($this->headers) > 0)
        {
            foreach ($this->headers as $header)
            {
                @header($header[0], $header[1]);
            }
        }

        // --------------------------------------------------------------------

        // Does the $CI object exist?
        // If not we know we are dealing with a cache file so we'll
        // simply echo out the data and exit.
        if ( ! isset($CI))
        {
            if ($this->_compress_output === TRUE)
            {
                if (isset($_SERVER['HTTP_ACCEPT_ENCODING']) && strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== FALSE)
                {
                    header('Content-Encoding: gzip');
                    header('Content-Length: '.self::strlen($output));
                }
                else
                {
                    // User agent doesn't support gzip compression,
                    // so we'll have to decompress our cache
                    $output = gzinflate(self::substr($output, 10, -8));
                }
            }

            echo $output;
            log_message('info', 'Final output sent to browser');
            log_message('debug', 'Total execution time: '.$elapsed);
            return;
        }

        // --------------------------------------------------------------------

        // Do we need to generate profile data?
        // If so, load the Profile class and run it.
        if ($this->enable_profiler === TRUE)
        {
            $CI->load->library('profiler');
            if ( ! empty($this->_profiler_sections))
            {
                $CI->profiler->set_sections($this->_profiler_sections);
            }

            // If the output data contains closing </body> and </html> tags
            // we will remove them and add them back after we insert the profile data
            $output = preg_replace('|</body>.*?</html>|is', '', $output, -1, $count).$CI->profiler->run();
            if ($count > 0)
            {
                $output .= '</body></html>';
            }
        }

        // Does the controller contain a function named _output()?
        // If so send the output there.  Otherwise, echo it.
        if (method_exists($CI, '_output'))
        {
            $CI->_output($output);
        }
        else
        {
            echo $output; // Send it to the browser!
        }

        log_message('info', 'Final output sent to browser');
        log_message('debug', 'Total execution time: '.$elapsed);
    }

这里主要注意的是压缩问题。

  1. $_SERVER[‘HTTP_ACCEPT_ENCODING’]是判断客户端是否支持压缩
  2. 如果支持压缩且需要执行php压缩代码,如果是缓存,发送相应请求头,不是缓存,执行php的压缩代码
  3. 如果不支持压缩,如果是缓存,则在执行php的解压缩代码再输出(因为缓存的内容会进行压缩),不是缓存,不执行压缩代码

3.写缓存_write_cache

缓存的目录可以是自定义目录,默认是’application/cache’目录

$path = $CI->config->item('cache_path');
        $cache_path = ($path === '') ? APPPATH.'cache/' : $path;

缓存的key是根据uri信息生成的md5字符串

$uri = $CI->config->item('base_url')
            .$CI->config->item('index_page')
            .$CI->uri->uri_string();

        if (($cache_query_string = $CI->config->item('cache_query_string')) && ! empty($_SERVER['QUERY_STRING']))
        {
            if (is_array($cache_query_string))
            {
                $uri .= '?'.http_build_query(array_intersect_key($_GET, array_flip($cache_query_string)));
            }
            else
            {
                $uri .= '?'.$_SERVER['QUERY_STRING'];
            }
        }

        $cache_path .= md5($uri);

$this->_compress_output为true对输出内容执行php压缩代码

if ($this->_compress_output === TRUE)
        {
            $output = gzencode($output);

            if ($this->get_header('content-type') === NULL)
            {
                $this->set_content_type($this->mime_type);
            }
        }

缓存有效时间以秒为单位,缓存有效时间和请求头信息,以序列化后的数组存入缓存中,并以’ENDCI—>’字符串为分割符合输出内容分开


$expire = time() + ($this->cache_expiration * 60); // Put together our serialized info. $cache_info = serialize(array( 'expire' => $expire, 'headers' => $this->headers )); $output = $cache_info.'ENDCI--->'.$output;

最后将缓存内容写入缓存文件

    /**
     * Write Cache
     *
     * @param   string  $output Output data to cache
     * @return  void
     */
    public function _write_cache($output)
    {
        $CI =& get_instance();
        $path = $CI->config->item('cache_path');
        $cache_path = ($path === '') ? APPPATH.'cache/' : $path;

        if ( ! is_dir($cache_path) OR ! is_really_writable($cache_path))
        {
            log_message('error', 'Unable to write cache file: '.$cache_path);
            return;
        }

        $uri = $CI->config->item('base_url')
            .$CI->config->item('index_page')
            .$CI->uri->uri_string();

        if (($cache_query_string = $CI->config->item('cache_query_string')) && ! empty($_SERVER['QUERY_STRING']))
        {
            if (is_array($cache_query_string))
            {
                $uri .= '?'.http_build_query(array_intersect_key($_GET, array_flip($cache_query_string)));
            }
            else
            {
                $uri .= '?'.$_SERVER['QUERY_STRING'];
            }
        }

        $cache_path .= md5($uri);

        if ( ! $fp = @fopen($cache_path, 'w+b'))
        {
            log_message('error', 'Unable to write cache file: '.$cache_path);
            return;
        }

        if ( ! flock($fp, LOCK_EX))
        {
            log_message('error', 'Unable to secure a file lock for file at: '.$cache_path);
            fclose($fp);
            return;
        }

        // If output compression is enabled, compress the cache
        // itself, so that we don't have to do that each time
        // we're serving it
        if ($this->_compress_output === TRUE)
        {
            $output = gzencode($output);

            if ($this->get_header('content-type') === NULL)
            {
                $this->set_content_type($this->mime_type);
            }
        }

        $expire = time() + ($this->cache_expiration * 60);

        // Put together our serialized info.
        $cache_info = serialize(array(
            'expire'    => $expire,
            'headers'   => $this->headers
        ));

        $output = $cache_info.'ENDCI--->'.$output;

        for ($written = 0, $length = self::strlen($output); $written < $length; $written += $result)
        {
            if (($result = fwrite($fp, self::substr($output, $written))) === FALSE)
            {
                break;
            }
        }

        flock($fp, LOCK_UN);
        fclose($fp);

        if ( ! is_int($result))
        {
            @unlink($cache_path);
            log_message('error', 'Unable to write the complete cache content at: '.$cache_path);
            return;
        }

        chmod($cache_path, 0640);
        log_message('debug', 'Cache file written: '.$cache_path);

        // Send HTTP cache-control headers to browser to match file cache settings.
        $this->set_cache_header($_SERVER['REQUEST_TIME'], $expire);
    }

4.输出缓存内容——_display_cache函数

_display_cache会通过Key找到对应的缓存文件,然后取出缓存文件中的内容,查看缓存信息,反序列化缓存信息,得到缓存有效时间,判断缓存是否有效,无效则删除缓存,返回FALSE *$_SERVER[‘REQUEST_TIME’]参数是请求时间

        if ( ! preg_match('/^(.*)ENDCI--->/', $cache, $match))
        {
            return FALSE;
        }

        $cache_info = unserialize($match[1]);
        $expire = $cache_info['expire'];

        $last_modified = filemtime($filepath);

        // Has the file expired?
        if ($_SERVER['REQUEST_TIME'] >= $expire && is_really_writable($cache_path))
        {
            // If so we'll delete it.
            @unlink($filepath);
            log_message('debug', 'Cache file has expired. File deleted.');
            return FALSE;
        }

设置缓存请求头


// Send the HTTP cache control headers $this->set_cache_header($last_modified, $expire); // Add headers from cache file. foreach ($cache_info['headers'] as $header) { $this->set_header($header[0], $header[1]); }

输出缓存 在阅读CodeIngiter.php的时候,我们知道,如果对应请求有缓存的话,则不会初始化控制器,所以_display就是通过是否加载了控制器来判断输出的内容是不是缓存的

        // Display the cache
        $this->_display(self::substr($cache, self::strlen($match[0])));
    /**
     * Update/serve cached output
     *
     * @uses    CI_Config
     * @uses    CI_URI
     *
     * @param   object  &$CFG   CI_Config class instance
     * @param   object  &$URI   CI_URI class instance
     * @return  bool    TRUE on success or FALSE on failure
     */
    public function _display_cache(&$CFG, &$URI)
    {
        $cache_path = ($CFG->item('cache_path') === '') ? APPPATH.'cache/' : $CFG->item('cache_path');

        // Build the file path. The file name is an MD5 hash of the full URI
        $uri = $CFG->item('base_url').$CFG->item('index_page').$URI->uri_string;

        if (($cache_query_string = $CFG->item('cache_query_string')) && ! empty($_SERVER['QUERY_STRING']))
        {
            if (is_array($cache_query_string))
            {
                $uri .= '?'.http_build_query(array_intersect_key($_GET, array_flip($cache_query_string)));
            }
            else
            {
                $uri .= '?'.$_SERVER['QUERY_STRING'];
            }
        }

        $filepath = $cache_path.md5($uri);

        if ( ! file_exists($filepath) OR ! $fp = @fopen($filepath, 'rb'))
        {
            return FALSE;
        }

        flock($fp, LOCK_SH);

        $cache = (filesize($filepath) > 0) ? fread($fp, filesize($filepath)) : '';

        flock($fp, LOCK_UN);
        fclose($fp);

        // Look for embedded serialized file info.
        if ( ! preg_match('/^(.*)ENDCI--->/', $cache, $match))
        {
            return FALSE;
        }

        $cache_info = unserialize($match[1]);
        $expire = $cache_info['expire'];

        $last_modified = filemtime($filepath);

        // Has the file expired?
        if ($_SERVER['REQUEST_TIME'] >= $expire && is_really_writable($cache_path))
        {
            // If so we'll delete it.
            @unlink($filepath);
            log_message('debug', 'Cache file has expired. File deleted.');
            return FALSE;
        }

        // Send the HTTP cache control headers
        $this->set_cache_header($last_modified, $expire);

        // Add headers from cache file.
        foreach ($cache_info['headers'] as $header)
        {
            $this->set_header($header[0], $header[1]);
        }

        // Display the cache
        $this->_display(self::substr($cache, self::strlen($match[0])));
        log_message('debug', 'Cache file is current. Sending it to browser.');
        return TRUE;
    }

5.设置缓存请求头——set_cache_header函数

    /**
     * Set Cache Header
     *
     * Set the HTTP headers to match the server-side file cache settings
     * in order to reduce bandwidth.
     *
     * @param   int $last_modified  Timestamp of when the page was last modified
     * @param   int $expiration Timestamp of when should the requested page expire from cache
     * @return  void
     */
    public function set_cache_header($last_modified, $expiration)
    {
        $max_age = $expiration - $_SERVER['REQUEST_TIME'];

        if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $last_modified <= strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']))
        {
            $this->set_status_header(304);
            exit;
        }

        header('Pragma: public');
        header('Cache-Control: max-age='.$max_age.', public');
        header('Expires: '.gmdate('D, d M Y H:i:s', $expiration).' GMT');
        header('Last-modified: '.gmdate('D, d M Y H:i:s', $last_modified).' GMT');
    }
Scroll to Top