Green Acorn

Blog

Getting started with Memcached & PHP

In this basic tutorial, I am going to show you how to install and get started with Memcached using PHP.
Memcached is used to improve a web applications performance by storing an associative array of data in its memory. This is typically used to store database query results, therefore reducing the amount of queries to the database server.

Installing Memcached

To install Memcached on Linux, run the relevant command below:

  • Ubuntu – sudo apt-get install memcached
  • Gentoo – sudo emerge install memcached
  • Redhat – sudo yum install memcached

Memcached starts automatically each time the server boots up. The configuration file contains the IP address and the port Memcached will be bound to. Default values (127.0.0.1 and 11211) are fine for a standard setup.

To edit the configuration file, type the below on the command line:

sudo nano /etc/memcached.conf

Using PHP with Memcached

In order to store and retrieve data with PHP, I will need to connect to the Memcached server. To do this I will install the “Memcache” extension for PHP by running the below command.

sudo pecl install memcache

Below is a basic script that sets and gets an array. This is done by:

  • Defining the host and port (defaults from /etc/memcached.conf)
  • Initialising the Memcache class
  • Catching the connect method return value (true or false)
  • Using Memcache::set to store data by binding it to the ‘my_key’ key.
  • Using Memcache::get to retrieve the cached data
<?php

define('MEMCACHED_HOST', '127.0.0.1');
define('MEMCACHED_PORT', '11211');
 
$memcache = new Memcache;
$cacheAvailable = $memcache->connect(MEMCACHED_HOST, MEMCACHED_PORT);

$memcache->set('my_key', array('foo' => 'bar'), 0, 20); // expires in 20 sec
<?php

if($cacheAvailable) {
    echo "<h1>This is cached data</h1>";
    $data = $memcache->get('my_key');
}

if(!isset($data) {
    echo "<h1>This is fallback data</h1>";
    $data = array('foo' => 'bar');
}

echo "<pre>";
print_r($data);
echo "</pre>";

It’s that simple to get started with Memcached! Obviously this is just scratching the service, however this can be a useful and powerful tool for scalable web applications.

Author:
Posted in: PHP, Web Development

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>