Winn.ws

Memcache with Codeigniter

In one of my latest projects we are using memcache to store user data and other items that will improve user experience. The cache library i am using is one i found on the CI forms. The library offers two types of caching. One is file caching for static pages or static data like a query. Two is memcache much faster and for data that is needed on quickly, note that memcache is not intended for static page caching you will need to use file caching for that.

How to use this library.
Load the library.

$this->load->library('Cache');

Now, useMemcache

$this->cache->useMemcache(MEMCACHE_IP, MEMCACHE_PORT);

After that we can now save data to memcahce.

$data = array('name' => 'Greg', id => 190);
$this->cache->save($data["id"].'_user',$data,NULL,3600);
// ---------
// $this->cache->save(KEY, DATA, GROUP, TTL);

If you plan on using file caching you do not need the “useMemcache()” file caching is on by default. But if you want to use both you can just call “useFile()” to switch back to files. Example below:

$this->cache->useMemcache(MEMCACHE_IP, MEMCACHE_PORT);
$data = array('name' => 'Greg', id => 190);
$this->cache->save($data["id"].'_user',$data,NULL,3600);
// Data above saved to memcache
 
$this->cache->useFile();
$data = array('name' => 'Greg', id => 190);
$this->cache->save($data["id"].'_user',$data,NULL,3600);
// Data above saved to file.

Now lets retrieve the data from the cache.

$this->cache->get(KEY);
 
// In my case above...
 
$user = $this->cache->get('190_user');
echo $user->id;
// would be 190

Download Cache.php library for Codeigniter.

posted in: Development, WordBoxes 01.02.10