Speed up slow pages with Memcache

Caching can really help speed matters on on a webpage. Especially when you have a big ass property search going on with umpteen joins etc. Sometimes it’s just easier to cache the results (for a suitably reasonable time). So lets do just that. If you haven’t got memcache installed, search my blog for my post manually compiling php modules successfully (justr search ‘successfully’). Once you’ve done that, it’s a piece of cake!

$cache_key = $area;

 $memcache = new Memcache;
 $memcache->connect('localhost', 11211) or die ("Could not connect");

 $cache_value = $memcache->get($cache_key);
 $db = new Application_Model_DbTable_Property();
 $props = $db->areaSearch($area);
 $cache_value = $props->count();
 $memcache->set($cache_key, $cache_value, false, (60*60*24)) or die ("Failed to save data at the server");
 return $cache_value;

And thats it! We give each query we need a unique key, in the example it is whatever $area is (Scotland!) and try to retrieve it. If there  is nothing returned, we do our query and store the result. The 60*60*24 (thats in seconds by the way) is the time until the cache expires, upon which it will return nothing again and refresh the query and cache. It really is that easy! Have fun!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s