Iamzozo
Iamzozo

Reputation: 2358

Codeigniter page cache when using custom _output method

I would like to cache my pages, which could be done by using:

$this->output->cache(n)

As in the documentation, i could use a custom output method in my controller, named _output.

The problem is, when I create this _output method in my controller, it doesn't create any cache file, only displays the output. I looked into the Output core class, and as I see if it's not find any method with _output, it just echo the content.

They have this in the documentation, to use in my _output:

if ($this->output->cache_expiration > 0)
{
   $this->output->_write_cache($output);
}

But cache_expiration is not accessible...

Upvotes: 1

Views: 396

Answers (1)

tomexsans
tomexsans

Reputation: 4527

You have 2 ways of solving this,

  1. you can edit the core files and make it the cache_expiration to public instead of protected and mess with the core files (DIRTY WAY)
  2. or you can extend the CI_Output class (BETTER)

Create a file name it MY_Output.php in your application/core the MY_ prefix is found on the $config['subclass_prefix'] option in your application/config/config.php file.,

then put this little piece of code:

class MY_Output Extends CI_Output{

    public $the_public_cache_expiration_ = 0;

    public function get_cache_expiration()
    {
        $this->cache_expiration_ = $this->cache_expiration;
    }
}

What we are doing is we are extending the CI_Output class and adding our very own method, when the method get_cache_expiration() is called it will assign the cache_expiration to the_public_cache_expiration_, use it on your _output.

test it using this:

public function _output($output)
    {
        $this->output->get_cache_expiration();
        echo '<pre>';
        print_r($this->output->the_public_cache_expiration_);//get only our cache expiration
        echo '<hr>';
        print_r($this->output);//print the whole Output class
    }   

benefits:

  1. We did no mess with the core files.
  2. we can add more functionality later to our child class.

here is the basic _output method in use

public function _output($output)

    {
        $this->output->get_cache_expiration();

        if($this->output->cache_expiration_ > 0)
        {
            $this->output->_write_cache($output);
        }

        echo $output;
    }

Upvotes: 1

Related Questions