Speed up your CakePHP application by using Memcached

In anticipation of heavier traffic and also just for performance reasons, I’ve started looking into ways of caching data for Nouchi.Mobi. Since this is a CakePHP application, I naturally looked into PHP cache based solutions and you’d be hard pressed not be recommended Memcached(Used by Facebook, Twitter, Youtube, Flicker amongst others). Why would you want database caching? If you’re using a framework to build your application or just from building any type of decently functional custom coded dynamic application nowadays, chances are you will make numerous calls to retrieve the data you want to display (the average Drupal site issues 300/400 queries!). Some pages do actually make more SQL queries than others and caching the result of these queries would give your application a significant performance boost. Memcached is a high performance in-memory data caching system that works by storing data as key-value pairs, meaning :

  • Store the value V with the key K
  • Retrieve the Value V identified by the key K

In the context of CakePHP, follow these instructions to get Memcached up and running in your local development environment. The trickiest steps in this set up will probably enabling the memcache support in your PHP configuration (getting and enabling the php_memcache.so extension in Linux). Keep in mind that for your production environment, unless you have your own Virtual Private Server, you’d be hard pressed to find any  host that will let you run Memcached in a shared hosting environment, but this is a scaling issue, and a problem you want to have, meaning your application is getting popular. Next you’d need to enable it in CakePHP in your app/core.php

Cache::config('default', array('engine' => 'Memcache'));

Once it’s up and running what you have to remember about using caching is that it is not magic. You have to code with caching in mind, and caching works best for queries that return the same data or that don’t change often. Teknoid has a good article on explaining what I mean by that with an example. Hope that’s enough to get you started and you can also take a look at this excellent Nettuts tutorial on the matter.

Advertisement

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

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

Facebook photo

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

Connecting to %s

%d bloggers like this: