November 27, 2013

November 27, 2013
In this article, we are going to discuss about How to implement memcache in CodeIgniter (CI). Memcache is used to increase the performance of the websute (ie, speed-up the website) by using the memory space of our used domains and store the database query results in that cache and minimise the application-database interaction.

Step 1:

Before we implement Memcache in CodeIgniter (CI), we need to check whether the memcache is enabled in our web server or not. If it is not enabled, then enable it by uncomment the 'extension=php_memcache.dll' in php.ini file in the server. (Just remove the ";" symbol infront of the line).

Step 2:

Download the Memcache executable file to install the Memcache in the webserver. To download the Memacache executable file, Click on the below link

Download link - http://code.jellycan.com/files/memcached-1.2.6-win32-bin.zip

Step 3:

Once downloaed, Unzip the downloaded file, you will get a memcached executable file. Store that in a web server to install.

Step 4:

Then open the command prompt and run this command

c:/xampp/htdocs/memcached.exe -d install

then run the below command

'c:/xampp/htdocs/memcached.exe -d start'

Step 5:

Download the cache driver from the below URL

http://d45jz936mo8n8.cloudfront.net/wp-content/uploads/2010/01/Cache.php_1.zip

Once downloaded, Unzip and place the cache.php in system/libraries/cache folder.

Step 6:

Create an empty folder named "cache" on the location system folder.

Step 7:

Load the Cache driver in controller CodeIgniter (CI) application

$this->load->driver('cache');

Add the following lines of code where needed to cache the query result.

$cache = $this->cache->get('cache_data');
if($cache)
{
  $data = $this->cache->get('cache_data');
}
else
{
   $data = $this->sample_model->get_data();
   $this->cache->save('cache_data', $data, NULL, 3600);
}

While accessing the webpage, it will execute query on the database for the first time, then the result will be stored in cache upto the refreshing time given in the save() function above.

So until the time exceeds, whenever the user refreshes the page, the application will not interact with the database. instead it will retrieve from cache and display.

This caching is applicable only for the select queries and the static updates.

0 comments:

Post a Comment