Register now and start sharing your code snippets.
-->
How to cache PHP objects to disk with CakePHP
PHP posted 11 months ago by christian
CakePHP has a view cache (similar to Rails) that can be used to cache objects. The following snippet shows a CakePHP action that uses the serialize and unserialize functions to cache a tag cloud—an array containing tags in this case—to disk, and then read it back.
Note that we assign a TTL of 1 hours to the tag cloud, so if it’s more than one hour old it will be refreshed from the database.
1 function index() 2 { 3 $maximum = 100; 4 $cache_key = "tag_cloud_$maximum"; 5 $tag_cloud = cache($cache_key, null, '+1 hours'); 6 7 if(empty($tag_cloud)) 8 { 9 $tag_cloud = Tag::generate_cloud($maximum); 10 cache($cache_key, serialize($tag_cloud)); 11 } 12 else 13 { 14 $tag_cloud = unserialize($tag_cloud); 15 } 16 17 return $tag_cloud; 18 }
The cache function is defined in $APP_ROOT/cake/basics.php, which is where you should look if you want to know more about how the caching works…