I’m using CakePHP1.2.5.
Cache is very powerful function for web pages using heavy SQL queries. If you use the CakePHP default Cache, you can see cache files in the app/tmp/cache directory.
I want to use the Cake Cache function at many points of my system and set different cache duration.
Firstly, check the core.php for using Cache.
//in core.php
Cache::config('default', array('engine' => 'File'));
This is a sample script using cache function, duration is 1 minute.
class PostController extends AppController {
var $uses = array('Post');
function index() {
$return_data = null;
Cache::set(array('duration' => '+60 seconds'));
if( ($return_data = Cache::read('PostController-index') ) === false ){
$return_data = $this->Post->find('all');
Cache::set(array('duration' => '+60 seconds'));
Cache::write('PostController-index' , $return_data);
}
$this->set('data',$return_data);
}
}
If there is no cache file(PostController-index),get DB data with the Post model and create cache file with its result. Array data is serialized.
You access same page within 1 minute, cake read cache file(PostController-index)
and return it insted of getting data from the Post model.
Key point is to use Cache::set() before each Cache::read and Cache::write(), we can change cache duration in each point.
http://book.cakephp.org/view/773/Cache-set
Be careful setting cache file name without overlap at each point. I recommend the rule, Class name + function name + parameter.
BTW, we can set Cache::config parameter in Cache::read() and Cache::write().
http://book.cakephp.org/view/766/Cache-read
http://book.cakephp.org/view/767/Cache-write
So, we can define multiple cache config as follow and use it each cache point.
//in core.php
Cache::config('default', array('engine' => 'File'));
Cache::config('onemin', array('engine' =>'File','duration'=> 60,));
Cache::config('onehour', array('engine' => 'File','duration'=> 3600,));
Cache::read('PostController-index', 'onemin')
Cache::write('PostController-index' , $return_data,'onemin');