Cache Results from Query in CakePHP

Posted on 03/24/2010 at 11:18 am by Kevin Wentworth
Viewed 14,999 times | 0 comments

I have a HUGE query that I wanted to cache.  I love CakePHP's caching functionality out of the box, but one thing is missing- you can't cache the results of a query.  Let me clarify.  You can cache the reults of a query, but only for that instance of a page load.  Using $this->cacheQueries only caches the query to memory, which only lasts for the duration of the page load.  If you want to cache query results to the file system, listen to Miles.

Cache Query Results in CakePHP

You'll need to add a function to your app_model.php, setup a Cache configuration and add a folder to your app/tmp/cache directory. After that, you can cache queries easily:

  1. $this->ModelName->find('all', array('cache'=>'cacheKey'));

One Modification (I couldn't resist)

Instead of checking if Cache.disabled is ===  false, I just changed it to a simple !Cache.disabled.  I did this so the function would work with how core.php ships, which has Configure::write('Cache.disable', true); commented out.  To recap:

  1. if (!Configure::read('Cache.disable') && ...
  2. //instead of
  3. if (Configure::read('Cache.disable') === false && ...

The above change is a mere matter of preference.

Get the Query Caching Code

Get the code at Miles' blog: query caching in CakePHP (a brilliant and simple approach!)

-Kevin Wentworth

Bookmark and Share

Tags for Cache Results from Query in CakePHP

Cakephp | Database | Web Programming | Usage | Example

Comments for this Posting

No comments. Be the first to post a reply.

Sorry, comments are closed for this posting.

Please Email Kevin if you have any questions. Thanks!

Meet Site Avenger - Hosted Content Management System

Powered By: Site Avenger | Site Production: Saco Design