Skip to content

Get Cache File Contents

Derek Jones edited this page Jul 5, 2012 · 6 revisions

Category:Library::Cache | Category:Library::Community

Here is an extension for the Output Library that aims to retrieve cached file contents and let you do fragment caching.

You just have to create a file called MY_Output.php in the system/application/libraries folder and put this code in the file :

[CODE] <?

class MY_Output extends CI_Output {

function My_Output()
{
    parent::CI_Output();
}

function get_cached_file&#40;$url&#41; {
        $CI =& get_instance();

        /* defines cache path */
        $cache_path = "system/cache/";
        if(strlen($CI->config->item('cache_path')) > 0) {
            $cache_path = $CI->config->item('cache_path');
        }

        /* retreives cache file */
        $cached_url = base_url().$CI->config->item('index_page')."/".$url;
        $cached_file = $cache_path.md5($cached_url);

        /* checks if cached file exists */
        
        if(file_exists($cached_file)) {
    
            /* gets cached content and removes timestamp */
            
            $handle = fopen&#40;$cached_file, "r"&#41;
            $contents = fread($handle, filesize($cached_file));
            fclose($handle);
            $timestamp_pos = strpos($contents, "---&gt;");
            $contents = substr($contents, ($timestamp_pos + 4));
            return $contents;
    
        }
    
        return FALSE;
}

}

?> [/CODE]

Then the usage is pretty simple. Imagine you've called the $this->output->cache(); function from the sample_controller, within the sample_method, then you would access this fragment this way:

[CODE] http://www.yoursite.com/sample_controller/sample_method/ [/CODE]

Then you can use the new get_cached_file function to get the cached contents of this page. And you can do it this way:

[CODE] $this->output->get_cached_file('sample_controller/sample_method') [/CODE]

Clone this wiki locally