Using Memcached in PHP for Faster Load Times

PHP and Memcached work together seamlessly for data caching. This article will step you through how to access and manage data within Memcached using PHP.

If you haven't done so yet, follow these instructions to install Memcached in a Windows or Linux environment.

The Data Set

When working with PHP and database results, I generally convert the results into an array that can be looped through using a simple for loop. For me, it's easier to maintain and read, and looping over array data is much simpler than looping over query data.

For the purposes of this article, we'll create a set of dummy data inside an array that we can easily loop through:

$my_array = [
[
"id" => 1,
"title" => "Orange"
],
[
"id" => 2,
"title" => "Banana"
],
[
"id" => 3,
"title" => "Apple"
]
];

Learn more about PHP arrays here if you're looking to learn about them or need to brush up on your skills.

Initialize Memached

Now, let's initialize Memcached. There are two lines of code required to do this:

$memcached = new Memcache;
$memcached->addServer("127.0.0.1", 11211);

The first command initializes a new Memcached instance, assuming that Memcached is running on the server. If it's not running and you try to run your PHP script, your whole page should error.

The second command creates a new Memcached instance to store data if it has not already been created. In the first argument, we're assigning 127.0.0.1 as the local IP address for the server location, and port 11211 as the port to access Memcached memory in the second argument.

If your page executes without an error message, then Memcached has been initialized successfully and we can move onto data management and caching.

Setting Memcached Data

First, let's set some data to a new Memcached key called "data". We'll use the $my_array variable's data above to store in this key:

$memcached->set("data", serialize($my_array), false, 300);

In this example, we're setting the $my_array data to a key named "data" that will be stored in Memcached memory.

The data will exist in memory for 300 seconds or 5 minutes. Once this timeframe has expired, the data will no longer be available in this key until it is stored again.

A few important things to note:

  • Make sure you're using unique key names when setting your data. If you use the same key name for different sets of data, the previous data attached to this key will only be available. Using the Memcached set() command overwrites any existing data within the specified key if it exists, or it creates a new data set.
  • Data stored in Memcached memory must be serialized to string format. Like browser cookies, complex objects cannot be stored. When accessing the data later, you must unserialize that data so you can access it as needed.

Reading Memcached Data

All Memcached data is stored within a unique key name. These key names are identified with a string value, like an ID to access the data.

Each key name is unique to one another and provides a different set of data that you store within each key.

Say we have a key with the name "data". If we wanted to access that key's data from Memcached, we could do so with these lines of code:

$my_data = $memcached->get("data");
$my_data = unserialize($my_data);

That's it! You now have a local copy of the Memcached key "data" stored in a local variable $my_data for use.

If you now loop through the data, assuming that our $my_array variable data was stored in Memcached at this key name, we could loop over it easily:

for ($i = 0; $i < sizeof($my_data); $i++) {
echo $my_data[$i]["id"] . ' - ' . $my_data[$i]["title"];
}

// 1 - Orange
// 2 - Banana
// 3 - Apple

I like to add a failsafe for Memcached data retrievals in case the data has not been stored at that specific key yet:

$my_data = $memcached->get("data");

if ($my_data) {
$my_data = unserialize($data);
} else {
$my_data = [];
}

This checks to make sure the retrieved data exists before accessing it locally, which prevents errors in your application.

Deleting Memcached Data

Deleting Memcached data is simple. All you need to do is call the Memcached delete() method and provide the key name:

$memcached->delete("data");

The data in the "data" key is now no longer available and cannot be accessed unless stored again under the same key name.

Flush All Memcached Data

If you want to just flush all of the data stored in Memcached, you can do so without providing a specific key name:

$memcached->flush();

Conclusion

Now that you have an understanding of Memcached and how it ties into PHP, you can easily optimize your applications for speed by storing your data resultsets into memory for a set period of time.

Published: December 16, 2020