March 3, 2021
Hot Topics:

Getting Started with Memcached Distributed Memory Caching

  • 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.


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.

Page 2 of 2

This article was originally published on September 1, 2010

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date