Caching Data Queries in CakePHP

In a recent CMS project in CakePHP I was loading in some data from a model to use nearly on every page. This data is not updated very often, so I figured I would cache the query. The method of caching data I am going to outline can be done not just for queries… but for any kind of data really. Lets get started!

The Cache Function

CakePHP’s cache function is quite easy to use. The code snippet below shows how to use it.

1
2
3
4
5
6
7
8
9
10
11
$cache_name = 'query';
$cache_data = Cache::read($cache_name);
if (empty($cache_data))
{
	$dataModel = $this->Model->find('first');
	Cache::write($cache_name, $dataModel, array('config' => 'File', 'duration' => 7200));
}
else
{
	$dataModel = $cache_data;
}

The code above attempts to read in the data from the cache, given the $cache_name. If the data is not found, the query is executed and then written to the cache. As you can see in the Cache::write I am using the File engine for caching, but you can use whichever you desire. I also set the duration to 7200 seconds (2 hours). If the cache data IS found then the query is skipped and the cache data is assigned to $dataModel. Pretty nifty eh?

I also believe that when you do a save operation on the Settings model Cake knows to automatically remove that cache data, so you don’t end up with out of sync info! If for some reason you want to manually delete the cached data you can use: Cache::delete($key) for a specific key, or Cache::clear() to delete everything in the cache.

Discussion (1)

  1. Great tip!

    Posted by TK | May 29, 2009, 9:48 pm

Post a comment