Saturday, February 19, 2011

Memcache with CakePHP

Hi,

Memcache simply means caching your query. This means that if you are caching your query then you do not need to make a database call every time. You need to run the database query once and set a refresh time. The next time, instead of the database the query will be fetched from the cache, thus improving the performance of the site. The refresh time is the frequency of refresing the content of the cache.

For achieving this you need to install memcache in the server. But CakePHP has a inbuilt caching system, which is similiar to conventional memcaching. Here I will discuss CakePHP's inbuilt memcaching system. In this you do not need to install memcache in your server.

Assuming you are using a model, Customer. The query you are using is:
select * from customers where age>55
In CakePHP you might write the following:

$output=$this->Customer->findall("Customer.age>55");

Now to convert this into cached query you just need to make the following changes:

$output=array();
if(!($output=Cache::read("customer_above55_cache")))
{
     $output=$this->Customer->findall("Customer.age>55");
    Cache::write("customer_above55_cache",$output,120);
}

The above code segment will make you query cached in CakePHP. "customer_above55_cache" is the name of the cache file, "120" is the number of seconds before refreshing the cache, Cache::read() is used to read the existing content of the cache, and Cache::write() to create the cache.

This is just a basic idea of memcache in CakePHP. With proper use you can literally make the user end of your website free of database calls. But for beginners it is highly advisable to use memcache for tables whose data are less volatile to change, such as the category table, which does not changes too often once the site is live.

The default path for memcached files is app/tmp/cache. Hope this article helps in performance optimization.

Cheers!!

No comments:

Post a Comment