Using Memcache With PHP

Using Memcache With PHP

1 Star2 Stars3 Stars4 Stars5 Stars
Posted on November 6, 2009

I want to just start this little post with that fact that I don’t know all the ins and outs of using Memcache but I have enough knowledge to just about get it working. I have access to a Mediatemple Dedicated Virtual Extreme server and managed to install it on the server using SSH, with the help of this little guide from Mediatemple which runs you through the installation process step by step.

Who uses Memcache?

Memcache was developed by Danga Interactive to enhance the speed of LiveJournal.com, Memcache dropped the database load to almost nothing, yielding faster page load times for users, better resource utilization, and faster access to the databases on a Memcache miss. Currently FaceBook are the biggest users of Memcache. Infact FaceBook are using it so aggressively that they are chartering new territory, and helping to develop the open source project.

fb

What’s Memcached?

So your reading this wondering what I’m talking about. Memcache is basically is a generalpurpose distributed memory caching system, put that in English, it allows you to store any form of data in a ‘temporary cache’ so wherever you go to do a database query, instead of just connecting to the database and getting the data we want we first check the memcache to see if our data is already stored. If the memcache returns nothing, then go to the database, get what you’re looking for, then store it in the memcache for later:

There are five main functions that we use with Memcache and they are as follows:

  • get() – gets the value for a specified key
  • set() – sets a given key with a given value
  • add() – adds to the cache, only if it doesn’t already exist
  • replace() – sets in the cache only if the key already exists
  • flush() – removes all keys and cached data

mem1

The Code

So once you have Memcache installed on your server you can connect to it and start caching stuff. It’s worth pointing out that you shouldn’t go out and cache everything, it’s really only useful when you have large amounts of data that are going to be requested regularly.

  1. So the first two lines setup the connection to Memcache.
  2. The include is just my database connection script.
  3. Next we set the key. When we store data using Memcache there are 3 parts to storing the data, those three parts are the key, the value, and the expiry time of the cached item. The key is used to reference the stored data. in this example you can see that the key is an MD5 hash of the database query.
  4. we then check if the key exists in the cache. this will return true or false. if the data is found in the cache then we can access it.
  5. If the data isn’t found in the cache we connect to the database to get it. we store the data in the cache by using the follow line: $memcache->set($key, $row, TRUE, 20); $row refers to the array that we get from the database, notice the 20 at the end. This refers to the how long this item will expire in the cache. It is measured in seconds.

$memcache = new Memcached();
$memcache>connect('127.0.0.1', 11211) or die ("Could not connect");

include('includes/connect.php');

//set the key then check the cache
$key = md5("SELECT * FROM memcached_test where name='ashley'");
$get_result = $memcache>get($key);
if ($get_result) {
echo $get_result['name'];
echo $get_result['username'];
echo "Data Pulled From Cache";
}
else {
 // Run the query and get the data from the database then cache it
 $query="SELECT * FROM memcached_test where name='ashley';";
 $result = mysql_query($query);
 $row = mysql_fetch_array($result);
 print_r($row);
 $memcache>set($key, $row, TRUE, 20); // Store the result of the query for 20 seconds
 echo "Data Pulled from the Database";
}

This is a very simple example of how to use memcache, but I hope it has been an insight into how caching works.

More tutorials from Papermashup
Comments
21 discussions around Using Memcache With PHP
  1. Techie Talks says:

    I think your sample has some problem… It should be $memcache = new Memcached(); instead of $memcache = new Memcache;

  2. Murugan says:

    Thank you for sharing this. Its really helpful.

  3. phpcoder says:

    You could have also pointed out how to install and set up memcache aswell

  4. Fantastic informative post. It’s really great….

  5. mike says:

    thanks for you. i’m really deal with large amount of data.this is the best solution for my project

  6. cutecankil says:

    nice and interesting keep it up!!

  7. ganesamoorthi says:

    Hi
    This is very useful information of php developer,
    I tried to install mamcache in xampp, but i got some error, please help me how to do that one.

    Thanks,
    Ganesamoorthi.D

  8. raj says:

    thanks a lot man . its really good about you sharing it

  9. Thiago Belem says:

    Great! Rly nice tutorial.. :)

    Just FYI: there’re some encoded html entities on your block of code like $memcache->connect

  10. MukulBD says:

    very useful tuts. Thanks for sharing..

  11. Very useful information i discover…
    Thanks,,,

  12. Raja says:

    Hi,

    This is very useful to me. Provide the link to know further more…..

    Thank you so much….

  13. styx says:

    Short and understandable … thanks for sharing

  14. HeartDisk says:

    hmmm thanks for sharing

  15. Nice and informative article. Very cool to know something new. Thanks to sharing this nice post. :)

  16. Paul du Long says:

    I have some trouble installing memcache on my server. Can you help please :)

  17. Davinder says:

    Wow, Thank you for this!
    I was looking for something like this.

  18. Enatom says:

    Wow, its great to know such technology exists. Seems a little advanced for me. But now know, i’d probably come across this in the near future, with my social networking app.

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Looking for a registry cleaner to speed up your PC and show a full diagnostics?
Faster surfing with Dish Network High Speed Internet

Never miss an update from Papermashup

Get notified about the latest tutorials and downloads.

Subscribe by Email

Get alerts directly into your inbox after each post and stay updated.
Subscribe
OR

Subscribe by RSS

Add our RSS to your feedreader to get regular updates from us.
Subscribe

Get in contact

Please use the form below to get in touch.

About Me

I'm Ashley Ford, Co-founder and Technical Director at Harkable.com London, UK. Previously I worked at InMobi, Spotify and MySpace. My interests include photography and making short videos I'm also an avid F1 fan. I'm always working on side projects. Here are a few: Easy Poll, We Deliver.



What do you specialise in?

I spend a lot of time coding in PHP and MySQL, as well as front end XHTML and CSS. I also specialise in javascript and the jQuery framework as well as being an avid designer. You can find me on dribbble

Interested in advertising?

If you'd like to advertise on Papermashup.com you can find details here Or use the contact link below for further advertising opportunities.

How do I contact you

You can contact me here. and I'm available for consultation, freelance, programming book reviews.

Get on the mailing list

Join over 3000 people who have subscribed to the Papermashup inbox message, and be the first to find out about tutorial, competitions and giveaways.