September 20, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Getting Started with Memcached Distributed Memory Caching

  • September 1, 2010
  • By Sachin Khosla
  • Send Email »
  • More Articles »

Memcached Code in Action

Let's see some Memcached code in action and learn how to make it work using the PHP code snippet below. It is a class that shows how to retrieve data from the cache. If that data does not exist, then it queries the database and stores it to cache for subsequent usage.

<?phpclass MyCache{  private $cache;  function  __construct()  {    $this->cache = new Memcache();    // you can replace localhost by Memcached server IP addr and port no.    $this->cache->connect('localhost', 10987);  }  function get_data($key)  {    $data = $this->cache->get($key);    if($data != null)      return $data;    else    {      if($this->cache->getResultCode() == Memcached::RES_NOTFOUND)      {        //do the databse query here and fetch data        $this->cache->set($key,$data_returned_from_database);      }      else      {        error_log('No data for key '.$key);      }    }  }}$cache = MyCache();$cache->get_data('foo');?>

To use this code in your development, make sure you have installed the Memcached PHP extension. In the latest version of PHP the extension is bundled with the PECL and PEAR packages.

Summary

Memcached is a powerful tool that various Web applications such as Wikipedia, Flickr and Digg all use. If using Memcached can dramatically increase the performance of Web applications like these, what are you waiting for?

About the Author

Sachin Khosla is a Web developer, open source technology evangelist and writer. Read his blog at digimantra.com.


Tags: caching, Memcached



Page 2 of 2



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel