Caching using memcache

suggest change

Memcache is a distributed object caching system and uses key-value for storing small data. Before you start calling Memcache code into PHP, you need to make sure that it is installed. That can be done using class_exists method in php. Once it is validated that the module is installed, you start with connecting to memcache server instance.

if (class_exists('Memcache')) {
  $cache = new Memcache();
  $cache->connect('localhost',11211);
}else {
  print "Not connected to cache server";
}

This will validate that Memcache php-drivers are installed and connect to memcache server instance running on localhost.

Memcache runs as a daemon and is called memcached

In the example above we only connected to a single instance, but you can also connect to multiple servers using

if (class_exists('Memcache')) {
  $cache = new Memcache();
  $cache->addServer('192.168.0.100',11211);
  $cache->addServer('192.168.0.101',11211);
}

Unlike connect(), addServer() does not open a connection until you store or fetch a value.

Caching needs three operations:

  1. Store data : Add new data to memcached server
  2. Get data : Fetch data from memcached server
  3. Delete data : Delete already existing data from memcached server

Store data

The Memcache object has a set method. The third argument is a flag (use 0 here) and the fourth is the time to live in seconds.

$cache->set($key, $value, 0, $ttl);

Here $ttl or time to live is time in seconds that you want memcache to store the pair on server.

Get data

get takes a key and returns the stored value.

$value = $cache->get($key);

If the key is missing, get returns false, not null. A stored false cannot be distinguished from a miss.

Delete data

To delete a cached value, call delete on the Memcache instance.

$cache->delete($key);

Small scenario for caching

Let us assume a simple blog. It will be having multiple posts on landing page that get fetched from database with each page load. In order to reduce the sql queries we can use memcached to cache the posts. Here is a very small implementation

if (class_exists('Memcache')) {
  $cache = new Memcache();
  $cache->connect('localhost',11211);
    if (($data = $cache->get('posts')) !== false) {
      // Cache hit
      // Render from cache
    } else {
      // Cache miss
      // Query the database and store the result in the cache
      // Assuming $posts is the array of posts retrieved from the database
      $cache->set('posts', $posts, 0, $ttl);
    }
}else {
  die("Error while connecting to cache server");
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents