Skip to Content

How to Use 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.  Then come back to this article to for optimizing your application speeds for faster load times.

Advertising Disclosure: I am compensated for purchases made through affiliate links. Click here for details.

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 how Memcached works with PHP, you can easily optimize your applications for speed and faster load times by storing your data resultsets into memory for a set period of time.

Posted by: Josh Rowe
Created: December 16, 2020

Comments

There are no comments yet. Start the conversation!

Add A Comment

Comment Etiquette: Wrap code in a <code> and </code>. Please keep comments on-topic, do not post spam, keep the conversation constructive, and be nice to each other.