Memcache in PHP Beginners Tutorial – A Practical Example

The aim of this tutorial is to introduce you to Memcache and how to make basic use of it in PHP. If you don’t know how to install Memcache, check out “Installing Memcache for Apache on Windows”. This tutorial covers:

  • Connecting to a Memcache server.
  • Setting a Memcache item.
  • Getting a Memcache item.
  • Doing something useful with it all.

We are going to fetch a number of options from our database that will populate a form select menu. The options in this particular select menu do get updated, but very rarely.

To save our database a tiny bit of extra work, we will implement Memcache to store those options in memory (a global server cache) as opposed to having to fetch them from the database every time the user loads the page.

This makes perfect sense really, why keep hitting the database for data that never/rarely ever changes?

Here is the full code that we will go through line by line:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?PHP
$MC = new Memcache;
 
$MC->addserver('localhost');
 
if (!$options = $MC->get('CACHED_OPTIONS')) {
 
    $conn = new PDO('mysql:host=localhost;dbname=tutorials', 'root', '');
    $results = $conn->query('SELECT id, name FROM options');
    $options = $results->fetchAll();
 
    $MC->set('CACHED_OPTIONS', $options);
}
?>
 
<select>
    <?PHP foreach ($options as $option) { ?>
        <option value="<?PHP echo $option['id']; ?>"><?PHP echo $option['name']; ?></option>
    <?PHP } ?>
</select>
<?PHP
$MC = new Memcache;

$MC->addserver('localhost');

if (!$options = $MC->get('CACHED_OPTIONS')) {

    $conn = new PDO('mysql:host=localhost;dbname=tutorials', 'root', '');
    $results = $conn->query('SELECT id, name FROM options');
    $options = $results->fetchAll();

    $MC->set('CACHED_OPTIONS', $options);
}
?>

<select>
    <?PHP foreach ($options as $option) { ?>
        <option value="<?PHP echo $option['id']; ?>"><?PHP echo $option['name']; ?></option>
    <?PHP } ?>
</select>

Line 2

We instantiate the Memcache class and assign it to a variable called $MC.

1
$MC = new Memcache;
$MC = new Memcache;

Line 4

Here we call the method addserver of our Memcache object. The addserver method takes nine parameters, but for this tutorial we are only interested in the first one. This is the address of the server where the Memcache service is running.

1
$MC->addserver($serverAddress);
$MC->addserver($serverAddress);

Line 6

The get method brings back stored data by key name, in our case CACHED_OPTIONS is (or will be) the index for our stored options.

1
if (!$options = $MC->get('CACHED_OPTIONS')) {
if (!$options = $MC->get('CACHED_OPTIONS')) {

This is then assigned to $options and if it’s false (i.e. nothing gets assigned to it) the code within is executed.

Lines 8, 9 and 10

Line 8 connects to the database using PDO, which is what you should be using as it is much safer than the old mysqli functions.

Line 9 executes our query and stores the results in our $results object.

Line 10  stores the results in an array called $options.

1
2
3
$conn = new PDO('mysql:host=localhost;dbname=tutorials', 'root', '');
$results = $conn->query('SELECT id, name FROM options');
$options = $results->fetchAll();
$conn = new PDO('mysql:host=localhost;dbname=tutorials', 'root', '');
$results = $conn->query('SELECT id, name FROM options');
$options = $results->fetchAll();

Lines 16 to 20

Now we just loop through each row and echo out the column names in the right place.

1
2
3
4
5
<select>
    <?PHP foreach ($options as $option) { ?>
        <option value="<?PHP echo $option['id']; ?>"><?PHP echo $option['name']; ?></option>
    <?PHP } ?>
</select>
<select>
    <?PHP foreach ($options as $option) { ?>
        <option value="<?PHP echo $option['id']; ?>"><?PHP echo $option['name']; ?></option>
    <?PHP } ?>
</select>

Now when the page is loaded the first time the data is retrieved from the database. For subsequent page loads by any client (remember this is a global cache, not per client), the data comes from cache!

You can test this all works by adding an echo “DB hit!” in underneath line 12 and adding an else to the if to echo “cache hit!”.

The data will always come from the cache until that cache server is restarted or the cache key is deleted using:

1
$MC->delete('CACHED_OPTIONS');
$MC->delete('CACHED_OPTIONS');

We must remember to delete the key CACHED_OPTIONS if we alter things in the database, otherwise users will still get the original and outdated option list.

This was a relatively trivial example of using Memcache. It really starts to shine when you cache complex queries such as counts and reports. For instance, we could use Memcache to accelerate pages that show a count of repeat customers for a given month.

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 lang=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" extra="">