Thursday, April 4, 2013

Install and Configure Memcache/Memcached on Windows and CodeIgniter

I recently spent some time installing and configuring Memcache/Memcached on windows and codeigniter. There are some issues in the configuration i.e. CI supports Memcached and Windows support Memcache. So thought of sharing the steps.

First of all let's install Memcached. You can download Memcached from http://code.jellycan.com/files/memcached-1.2.6-win32-bin.zip

Unzip the file in some directory (let's say C:\Memcached). Open command prompt as Administrator. Point to the C:\Memcached directory. Next step is to install Memcached, you can do that by using following command:

c:\Memcached\memcached.exe -d install

Next step is to run memcached server. Use following command to do that

c:\Memcached\memcached.exe -d start

This will run the memcached server on port 11211. Now, let's configure php to run memcached. Open php.ini file and find ;extension=php_memcache.dll. If you find this line then simply remove semicolon from the start of line. If you don't find this line then add it at the end of extensions section. After extensions section, add a new line and paste following:

[Memcache]
memcache.allow_failover = 1
memcache.max_failover_attempts=20  
memcache.chunk_size =8192  
memcache.default_port = 11211

Next step is to download php_memcache.dll file. You can download the file from http://downloads.php.net/pierre/ . Unzip the php_memcache.dll file and place it in php/ext/ folder.

Now, let's configure CI to run memcached. Create memcached.php file in application/config folder and place following code in it:

<?php

  if (!defined('BASEPATH')) exit('No direct script access allowed');

    $config['memcached'] = array(
        'hostname' => '127.0.0.1',
        'port'        => 11211,
        'weight'    => 1
    );

?>

Next, open \system\libraries\Cache\drivers\Cache_memcached.php file and in the function is_supported(), replace following line
if ( !extension_loaded('memcached'))
with
if ( !extension_loaded('memcached') && !extension_loaded('memcache'))
.Then in _setup_memcached() function, replace following line:
$this->memcached = new Memcached();
with:
if(class_exists("Memcached"))
  $this->_memcached = new Memcached();
else
  $this->_memcached = new Memcache();

Now, restart apache and create a test function in CI controller and paste following code in it to give it a try:

$this->load->driver('cache',array('adapter'=>'mecached'));
$this->cache->memcached->save('foo', 'bar', 10);
echo $this->cache->memcached->get('foo');

You can find the details of Cache plugin in CI at http://ellislab.com/codeigniter/user-guide/librarie/caching.html