Nov 132014
 
Article PHP

If there is enough main memory available in the server where an application is running, a memory cache can significantly improve the performance of the application.

This post is a tutorial on how to install a “memcached” service on a server running linux Debian, and how to use the service in a PHP script.

1. Installing the memcached service

memcached can be found as a module in the standard Debian repository. Therefore, it can be easily installed with “apt-get”:

$ sudo apt-get install memcached
   ...
Setting up memcached (1.4.13-0.2+deb7u1) ...
Starting memcached: memcached.
$

memcached is installed as a service, and can thus be started and stopped using the “service” command:

$ sudo service memcached status
[ ok ] memcached is running.
$ sudo service memcached stop
Stopping memcached: memcached.
$ sudo service memcached start
Starting memcached: memcached.
$

Additionally, the installation adds a script /etc/init.d/memcached, to allow the service to start on system boot.

2. Using memcached from a PHP script

2.1. Installing the php5-memcached module

To use the memcached service in a PHP script, there are two options: Use the older “php-memcache” extension, or else the new “php-memcached” extension, that adds extra functionality. This post explains how to use the second module.

The first step is the installation of the extension. As before, a call to apt-get can be used for this installation:

$ sudo apt-get install php5-memcached

 2.2. Test script

To test the functionality, a simple script can be used, as follows:

<?php

// Connect to the memcached service
$cache = new Memcached();
$cache->addServer("127.0.0.1", 11211);
 
$key = "test_key";
$result = $cache->get($key);
 
if($result) {
  echo "Value read from cache: " . $result . "\n";
} else {
  echo "No data found in Cache for key: " . $key . ".\n";
  $cache->set($key, "Test value") or die ("Error storing data in memcache");
}

The fist time the test script is run, the output is:

$ php test_memcache.php 
No data found in Cache for key: test_key.
$

The second time the test script is run, the output is:

$ php test_memcache.php 
Value read from cache: Test value
$

3. Configuring memcached

The configuration of the memcached service is in the file /etc/memcached.conf

Among other, the main parameters that can be tweaked in that file are:

– The maximum amount of RAM memory used by the service. The default value is 64 MB (-m 64)

– The IP address and TCP port where memcached will listen for requests. The default is localhost (-l 127.0.0.1), port 11211 (-p 11211)


References


 

Index of posts on PHP programming


 

 Posted by at 4:52 pm

 Leave a Reply

(required)

(required)