Introduction to Memcached and how to use it with PHP

Hello all,
today I am going to talk about Memcached how to install/configure and using it along side with with PHP and any database, lets start.

memcached

What is Memcached?

Memcached is a general-purpose distributed memory caching system. It is often used to speed up dynamic database-driven websites by caching data and objects in RAM to reduce the number of ti-mes an external data source (such as a database or API) must be read
Wikipedia: Memcached

Memcached is an in-memory key-value store for small chunks of arbitrary data (strings, objects) from results of database calls, API calls, or page rendering.
Memcached

So Memcached is a key-value store for small chunks of data “1MB” in RAM, then you can access these data any time from the RAM instead of querying the database again or read them from cached files, and of course all the data going to be deleted when you switch of your machine, also Memcached has the ability to distribute these keys/values in multiple servers. Memcaced is intended for use in speeding up dynamic web applications by alleviating database load.

How to Install Memcached

sudo apt-get install memcached

This command going to install memcached and you can now use telnet to connect to it and start setting/getting values

telnet localhost 11211

But in this tutorial we are going to use libmemcached-tools which is a command line tools for talking to memcached so go ahead and type

sudo apt-get install libmemcached-tools

after installing libmemcached-tools now we have some tools that we can use from the command line like memccat, memcdump, etc, we are going to use some of them for the sake of testing and debugging.

Creating Your First Memcached Record

First of all we are going to make new file called product and echo any value into it “190”
the second command memccp which take we specified out server to be localhost as we installed memcached locally and the third option is the file name

echo "190" > product
memccp --servers localhost product

now we stored a new key-value in memcached with the file name as a key and file contents as a value; what about retrieving it? to retrieve a value from memcached we use the command memccat

memccat --servers localhost product

This command going to output the value that we just added which is 190.

Some useful command that you can use is also memcdump which is useful for debugging as it is going to dump all the keys in memcached, memrm which is going to remove a specific key you provide, memcstat which going to display some statistics about memcached and finally memflush that can be used to invalidate all the keys on the server.

wanna try them?, run these commands one by one

#dump all the keys in the server
memcdump --servers localhost

#create new file
echo "80" > product80

#copy this file to memcached
memccp --servers localhost product80

#check the newly created key-value
memccat --servers localhost product80

#remove the newly created item
memcrm --servers localhost product80

#flush all the server
memcflush --servers localhost

#get the status
memcstats --servers localhost

 

Using Memcached with PHP

Now we know enough about memcached from the command line, what about creating our first php script to create/read/update/delete records from memcached.

First of all we have to install php5-memcache then restart your apache

sudo apt-get install php5-memcache
sudo service apache2 restart

create a new file in your www folder called memcached.php and add these line into it

//create a new object of memcache
$memcache = new Memcache;
 
//trying to connect to memcached server locally using port number 11211
$memcache->connect('localhost', 11211) or die ("Could not connect");
 
//store new value
$memcache->set("key", "value");
 
//retrive the previouly created value
$result = $memcache->get("key");
 
echo $result;

In the previous example we created a new memcache object and then used the method connect to make a connection with our server, we can also use the method addServer() to add as many servers as we want.

Then we used the method set() to set a new key, the method set() take two parameters key & value and could take more parameters for the expiration date of the item if you want.

finally we retrieved the newly created item by using the method get() which take the key of the item that we want to retrieve as a parameter.

Real World Example

Now we have created a simple PHP write/read example to demonstrate how to usage of memcached now we are going to create a better example that we may use something like it in our websites.

Suppose we have a page the display some information about specific product, each time a user open this page we query the database to get these data,  we want to cache these data instead of querying the database every time.

First of all I am going to create a method to retrieve the product from the database and for the sake of simplicity I am not going to query the database am just going to return an array of some dummy data

function get_product_data_from_db($product_id){
    //Simulate retrieving data from the database for simplicity.
    $product = array(
                  "product_id"  => $product_id,
                  "title"       => "Test Product Name",
                  "description" => "Some Description about this product",
                  "image"       => "http://www.example.com/url/to/the/product/image.jpg",
                  "price"       => "20.00",
              );
    //sleep for 5 seconds to simulate a waiting time.
    sleep(5);
    return $product;
}

Then I am going to create another method in the same file which we are going to use to retrieve the product data

function get_product($product_id){
    //connect to the memcached server
    //of course it is not the best place to make the connection
    //but I just created it here for the sake of simplicity again :).
    $memcache = new Memcache;
    $memcache->connect('localhost', 11211) or die("Could not connect");
     
    //get the product from the cache
    //going to return false if the key didn't exist on the cache
    $product_data = $memcache->get($product_id);
     
    //if product data isn't false then return it
    if($product_data)
        return $product_data;
         
    //else we are going to retrieve the data from the database
    $product_data = get_product_data_from_db($product_id);
     
    //store the reterieved data in the cache
    $memcache->set($product_id, $product_data);
     
    //return the data
    return $product_data;
}

Now we have a method which is used to get the data from the cache, and if it failed to retrieve it, It will get the data from the database and store it in the cache to use the cached version data in the next time.

Finally I am going to write a line of code to get product data and print it.
in the end of the file add

print_r(get_product(100));

Now point your browser to this page you will notice that the page going to take a little bit long time to load in the first time “due to the sleep(5)” which mean that it didn’t find the data in the cache and going to query the database to get it; then refresh the page again it should work fine because the data is in the cache now. if you refreshed the page again and again it will keep getting the data from the cache.

The full code

<?php
function get_product_data_from_db($product_id){
    //Simulate reteriving data from the database for simplicty.
    $product = array(
            "product_id"  => $product_id,
            "title"       => "Test Product Name",
            "description" => "Some Description about this product",
            "image"       => "http://www.example.com/url/to/the/product/image.jpg",
            "price"       => "20.00",
        );
 
    //sleep for 5 seconds to simulate a waiting time.
    sleep(5);
 
    return $product;
}
function get_product($product_id){
    //connect to the memcached server
    //of course it is not the best place to make the connection
    //but I just created it here for the sake of simplicity again.
    $memcache = new Memcache;
    $memcache->connect('localhost', 11211) or die("Could not connect");
 
    //get the product from the cache
    //going to return false if the key dont exist on the cache
    $product_data = $memcache->get($product_id);
 
    //if product data isn't false then return it
    if($product_data)
        return $product_data;
 
    //else we are going to retrieve the data from the database
    $product_data = get_product_data_from_db($product_id);
 
    //store the reterieved data in the cache
    $memcache->set($product_id, $product_data);
 
    //return the data
    return $product_data;
}
print_r(get_product(100));

In the next post I am going to talk about how to make this cache persistent, as you might know if you rebooted your computer all the data in the cache going to be deleted, simply because it is on the RAM.

That is all what I have for now, if you have any questions don’t hesitate and post your comment

Thanks!

You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *