CodeIgniter Forums
Cache just certain views only - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: Cache just certain views only (/showthread.php?tid=30430)



Cache just certain views only - El Forum - 05-14-2010

[eluser]Mr. Pickle[/eluser]
Is it possible to set a cache for seperate views?

The documatation about cache says
Code:
$this->output->cache(n);

But this doesn't tell me how to use and if it can be used to cache only certain views.

For example:

Code:
$this->load->view('header');     /** THIS I WANT TO CACHE **/
$this->load->view('user-info');  /** THIS I DON'T WANT TO CACHE, BECAUSE DIFF. 4 EACH USER **/
$this->load->view('content');    /** THIS I WANT TO CACHE **/
$this->load->view('footer');     /** THIS I WANT TO CACHE **/

Thanks!


Cache just certain views only - El Forum - 05-14-2010

[eluser]mddd[/eluser]
The basic cache function of CodeIgniter only caches the output of the whole page. This will not work for you if there is any information on the page that is different for one user or another.

I wrote some code for myself that looks at the variables in a certain view and caches that view, while keeping it separate from the same view when it has other data. Basically, it works like this:

Code:
$id = $some_id; // for instance, a user id when loading a user's profile

// now check if this view was already cached for this id
// build the filename for this cachefile. it is "nameOfView.idOfView"
$cachename = CACHE_FOLDER . 'profile.' . $id;

if (file_exists($cachename))
{
  // get the output from the cached file
  $output = file_get_contents($cachename);
}
else
{
  // get the data through a model
  $data = this->user_model->get_user_profile($id);
  // load the view
  $output = $this->load->view('profile', $data, true);
  // save the contents to a file for next time
  file_put_contents($cachename, $output);
}

Note: in reality you should also check if the file is not too old, and if the information is somehow changed (in this example: if a user changes their profile), you should delete the cachefile so it is loaded correctly with the new information the next time.

Also, you should look into existing libraries that do this kind of stuff. I'm sure it has been done before.