Cache principle decomposition of codeigniter framework

Source: Internet
Author: User
Tags flock md5 hash codeigniter

 

Purpose of Using Cache: (the manual describes the following, which has been clearly written)

Codeigniter supports the caching technology to achieve the fastest speed.

Although Ci has been quite efficient, factors such as the dynamic content in the webpage, the memory CPU of the host, and the read speed of the database directly affect the loading speed of the webpage. Depending on the Web cache, your web page can load almost static Web pages because they save the results output by the program to the hard disk.

 

How to use:

To enable the caching function, you only need to put the following code in the function of any controller:

$ This-> output-> cache (1 );

WhereNYou want the cache to be updated.MinutesNumber. You can use M/60 to get accurate to the second. For example, 1/60 is accurate to 1 second.

The above code can be put in any function. The order of appearance does not affect the cache, so place it where you think it is most logical. Once the above Code is put into the Controller method, the page will be cached.

Note:

Because CI stores cached files, only the output of view files can be cached, that is, $ this-> load-> View ('xxxx', $ data ); the third parameter cannot be true.

Make sure thatApplication/CacheFolder writable.

If you no longer want to use the cache, you only need to delete the above Code from your controller. Note: This will not cause the cached file to disappear immediately. It will automatically expire and be deleted. If you want to delete those files immediately, you must do it yourself.

 

 

Principle:

Use $ this-> output-> cache (1); to enable the cache:

Then make a judgment in codeigniter. php:

1 if ($EXT->_call_hook(‘cache_override‘) === FALSE)2     {3         if ($OUT->_display_cache($CFG, $URI) == TRUE)4         {5             exit;6         }7     }

The third line of code above, if the cache file is read successfully, the _ display_cache method will directly output the cache content, and then exit without executing it.

Read cache operation: (in the output class _ display_cache method)
Read the cached file. No false is returned.
Check whether the cache has expired when a cached file exists. If the cache expires, false is returned when the cached file is deleted.
No expiration. The returned value is false when the cached content is read.
 * Update/serve a cached file     *     * @access    public     * @param     object    config class     * @param     object    uri class     * @return    void     */    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;        $filepath = $cache_path.md5($uri);        if ( ! @file_exists($filepath))        {            return FALSE;        }        if ( ! $fp = @fopen($filepath, FOPEN_READ))        {            return FALSE;        }        flock($fp, LOCK_SH);        $cache = ‘‘;        if (filesize($filepath) > 0)        {            $cache = fread($fp, filesize($filepath));        }        flock($fp, LOCK_UN);        fclose($fp);        // Strip out the embedded timestamp        if ( ! preg_match("/(\d+TS--->)/", $cache, $match))        {            return FALSE;        }        // Has the file expired? If so we‘ll delete it.        if (time() >= trim(str_replace(‘TS--->‘, ‘‘, $match[‘1‘])))        {            if (is_really_writable($cache_path))            {                @unlink($filepath);                log_message(‘debug‘, "Cache file has expired. File deleted");                return FALSE;            }        }        // Display the cache        $this->_display(str_replace($match[‘0‘], ‘‘, $cache));        log_message(‘debug‘, "Cache file is current. Sending it to browser.");        return TRUE;    }

 


Write cache operation: (in the output class _ write_cache method)
Cached file name: MD5 value of Uri;
Cache content: Expiration timestamp Plus special characters 'ts ---> 'plus the template content after variable Parsing
Custom cache path
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();        $cache_path .= md5($uri);        if ( ! $fp = @fopen($cache_path, FOPEN_WRITE_CREATE_DESTRUCTIVE))        {            log_message(‘error‘, "Unable to write cache file: ".$cache_path);            return;        }        $expire = time() + ($this->cache_expiration * 60);        if (flock($fp, LOCK_EX))        {            fwrite($fp, $expire.‘TS--->‘.$output);            flock($fp, LOCK_UN);        }        else        {            log_message(‘error‘, "Unable to secure a file lock for file at: ".$cache_path);            return;        }        fclose($fp);        @chmod($cache_path, FILE_WRITE_MODE);        log_message(‘debug‘, "Cache file written: ".$cache_path);    }

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.