I'm planning on using caching in CakePHP. I'm wondering what happens if I updated the data on my tables, will CakePHP re-cache my data?
Thanks in advance!
I'm planning on using caching in CakePHP. I'm wondering what happens if I updated the data on my tables, will CakePHP re-cache my data?
Thanks in advance!
Not automagically, no.
Whatever you cache will not change until it expires or until you update it. That's sort of the point of a cache. The trick is to define a proper expiration timeframe and/or delete/refresh the cache when something changes that you want to be reflected immediately.
Let's say you have a blog and you need to cache the front page, because it receives ever so many hits and making a round-trip to the database every time would bring the server down. You can cache the page indefinitely, just whenever you create or edit a blog post, you clean the cache to force it to update.
Or, let's say you display a list of Twitter posts, which are constantly updating, but you can't refresh them every single time because Twitter imposes update frequency restrictions. Here you'll use a time limited cache, say 10 minutes, before checking for new posts.
Or, let's say, the pure operation of pulling some info out of the database is very expensive, so you don't want to do it every time, but you always need the latest data. In that case you make a small, inexpensive query to figure out if the data has changed since the last time you cached it (e.g. fetch the modified
timestamp field of a certain record), and decide based on this information whether to start the more expensive operation or just use the cached data.
The particular strategy depends on your situation.
There are several type of Cache methods and Cache Engines in CakePHP: http://book.cakephp.org/view/156/Caching
I'm using the default File Cache Engine. You can configure how long you want to cache your data in your core.php file. For example, I created a 'short' cache and a 'long' cache like this.
Cache::config('short', array(
'engine' => 'File',
'duration'=> '+1 hours',
//'path' => CACHE,
//'prefix' => 'cake_short_'
));
Cache::config('long', array(
'engine' => 'File',
'duration'=> '+1 week',
'probability'=> 100,
//'path' => CACHE . 'long' . DS,
));
So whenever you want to read or write a data to cache, you can specify this config name to know how long to cache. More info: http://book.cakephp.org/view/767/Cache-write