Getting Started with Caching in PHP using memcached

Caching is used to store the data which are frequently used. The main advantage of caching is that it increases the performance of the site or an application by decreasing the load on to the server like database.

There are different caching methods to cache the data like caching content in file, memory or database. Memcached is one type of memory caching system. It is very useful when large number of data you want to cache.

It is distributed memory caching system. Memcached is key-value store for caching small chunks of data from result of database, API or page rendering. Basically it can cache anything if you can turn it into key => value. Memcached solves many problems related to large data caching.

Memcached is better because of the following reasons:

  1. It’s REALLY fast – Everything’s in memory, and it’s highly optimized for situations just like yours (and caching in general )
  2. It’s distributed – This means that if you have multiple web / app servers running, they can all access the same cache
  3. You can pool multiple servers for memcached – If you’ve got a few servers that are relatively underutilized (or several dedicated cache servers), you can pool them all together into one big cache
  4. It’s super-scalable (for the reasons mentioned prior)
  5. It’s got great PHP support – The PECL package for memcached was recently updated with a lot of new goodness
  6. You can even store your user sessions in memcached – just set it up in your php.ini file. This is much faster than storing sessions in databases, and allows your sessions to persist across multiple web hosts (if you’re in a load balanced situation). This will also give your site a bit of a performance boost as there’s no need to hit the file system / database for session info on every request.

What memcached does?

Fig 1. Memcached Usage
  • In first case (without using memcached), there are two webservers (A and B). Each webserver is independent. If webserver ‘A’ uses less memory than, webserver ‘B’ can’t use the remaining memory. Means remaining memory spare is now wasteful. Webserver ‘B’ must have to use another 64 MB from other node.
  • While in second case (using memcached), both webserver (A and B) can use 128 MB memory, which is logically combined by memcached. Means the given item for caching from the server are stored on same location and always retrieved from the same location.

For example, If you have fifty web servers, you still have a usable cache size of 64MB in the first example, but in the second, you have 3.2GB of usable cache.

How memcached works?

Fig 2. Memcached Workflow
Fig 2. Memcached Workflow

The data which are frequently used and which are not going to be changed for long time, are stored using memcached.

Client request to server to get data from memcached, if requested data exists in memcached, it retrieve the data and send it to the client. But if data does not exist in cache, it will load data from the database or any other source. Then memcached server stores data in memcached and send to the client.

So each and every time you do not have to run database query and get data from database. Instead of going to database to get data you can fetch from memcached if exists. This technique allow you to build most optimized application.

Memcached installation on ubuntu

1)  Install Memcached

apt-get update
apt-get install memcached

2) Configuration of the Memcached Installation

memcached -h
# Default connection port is 11211
-p 11211

3)  Restart Memcached

service memcached restart

4)  Install the Memcached PHP Extension

apt-get update
apt-get install php5-memcached

5)  Verify Installation

php -m | grep memcached

Implementation in php

1) Create object of memcached

$memcached = new Memcached();

2) Store value in memcached

$result = (‘SELECT * FROM user’);
$user_data = $memcached->set(‘user_data’,$result);

3) Check if memcached has key

If ($memcached->get (‘user_data’))
return true;
return false;

4) Get data from memcached

$user_data = $memcached->get (‘user_data’);

Implementation in laravel

1) Change driver name in cache.php file located in config folder

‘default’ => env(‘CACHE_DRIVER’, ‘memcached’)

2) Change in .env file


3) Store data in memcached,

$expiresAt = 30; (in minutes)

4) Checking For Existence In Cache


5) Retrieving an item from cache

$value = Cache::get(‘key’);

6) Storing an item in the cache permanently


7) Removing item from the cache


* Cache tags are supported by memcached, for example:

$tag1= ‘getUserById’;
$tag2 = $user_id;
    $result = Cache::tags([$tag1,$tag2])->get(‘getUserByIdCache’);
    $result = DB::select(‘select * from user where user_id =?’,[$user_id]);

Here in tag based system, we can cache user data for each user separately. For example, there are 2 users and their user_id is ‘1’ and ‘2’. So that for user 1, there are two tags: first is ‘getUserById’ and second is ‘1’. And for user 2, also there are two tags: first is ‘getUserById’ and second is ‘2’.Thus, on the same key, user data will be cached using different tags.

The following statement is used to remove all user,



Warning: count(): Parameter must be an array or an object that implements Countable in /home/optimumbrew/public_html/blog/wp-includes/class-wp-comment-query.php on line 405

Leave a Comment