Quick Start
This guide covers the fundamental workflows for connecting to Memcached, storing data, retrieving data, and handling errors using the php-memcached extension.
Before running these examples, ensure you have a Memcached daemon running locally (usually on port 11211).
1. Connecting to Memcached
The first step is to instantiate the Memcached class and add servers to your connection pool. Memcached is distributed by design; the client handles hashing your keys to determine which server receives which piece of data.
<?php
// Instantiate the Memcached object
$cache = new Memcached();
// Add a server to the pool.
// Signature: addServer(string $host, int $port, int $weight = 0)
$cache->addServer('127.0.0.1', 11211);
// Alternatively, add multiple servers at once with varying weights
/*
$cache->addServers([
['10.0.0.1', 11211, 60], // 60% of the traffic
['10.0.0.2', 11211, 40] // 40% of the traffic
]);
*/
2. Basic CRUD Operations
Memcached operations are primarily Key-Value based. Keys are strings (maximum 250 characters, no spaces or control characters), and values can be almost any PHP data type.
<?php
$cache = new Memcached();
$cache->addServer('127.0.0.1', 11211);
$key = 'user_greeting';
// --- SET data ---
// Signature: set(string $key, mixed $value, int $expiration = 0)
// An expiration of 60 means the key expires in 60 seconds.
// 0 means it never expires (though it may be evicted if the server runs out of RAM).
$cache->set($key, 'Hello, Memcached User!', 60);
// --- GET data ---
$greeting = $cache->get($key);
echo "Greeting: {$greeting}\n";
// --- DELETE data ---
$cache->delete($key);
3. Working with Complex Data (Arrays & Objects)
You are not limited to storing strings. php-memcached automatically serializes and unserializes complex PHP data types for you.
<?php
$cache = new Memcached();
$cache->addServer('127.0.0.1', 11211);
$userProfile = [
'id' => 456,
'username' => 'johndoe',
'preferences' => [
'theme' => 'dark',
'notifications' => true
]
];
// The array is serialized (using PHP serialization, igbinary, etc., based on your config)
$cache->set('user_profile_456', $userProfile, 3600);
// When retrieved, it is automatically converted back into a PHP array
$cachedProfile = $cache->get('user_profile_456');
if ($cachedProfile) {
echo "Welcome back, " . $cachedProfile['username'] . "!\n";
}
4. Proper Error Handling
In a distributed caching environment, operations can fail for many reasons: network timeouts, memory limits, or missing keys. Never rely strictly on boolean false to detect a missing key, as false itself might be the actual value stored in the cache!
Instead, always use getResultCode() immediately after an operation to verify its success.
<?php
$cache = new Memcached();
$cache->addServer('127.0.0.1', 11211);
$value = $cache->get('potentially_missing_key');
// Check the result code of the last operation
$code = $cache->getResultCode();
if ($code === Memcached::RES_SUCCESS) {
echo "Cache HIT! Value: " . var_export($value, true) . "\n";
} elseif ($code === Memcached::RES_NOTFOUND) {
echo "Cache MISS! The key does not exist.\n";
// --> Logic to fetch data from your Database goes here <--
} else {
// Something else went wrong (e.g., server down, timeout)
echo "Cache ERROR: " . $cache->getResultMessage() . "\n";
}
5. Incrementing Counters
If you need to track numbers (like page views, rate limits, or inventory), do not use get() followed by set(), as this creates race conditions. Instead, use Memcached's atomic increment() and decrement() methods.
<?php
$cache = new Memcached();
$cache->addServer('127.0.0.1', 11211);
$key = 'page_views_home';
// Signature: increment(string $key, int $offset = 1, int $initial_value = 0, int $expiry = 0)
// This atomically increments the value by 1. If the key doesn't exist, it is initialized to 1.
$views = $cache->increment($key, 1, 1, 0);
echo "This page has been viewed {$views} times.\n";
Next Steps
Now that you understand the basics, check out the Usage Guide for production-critical topics like Persistent Connections, Consistent Hashing, and Multi-Operations.