Quick Start Guide
This guide provides a quick overview of the basic operations in APCu: adding, storing, fetching, checking, and deleting data.
Storing a Variable
The most common function is apcu_store(), which adds or overwrites a variable in the cache.
<?php
$favoriteColor = 'blue';
$key = 'user:123:color';
if (apcu_store($key, $favoriteColor)) {
echo "Data stored successfully!\n";
} else {
echo "Failed to store data.\n";
}
?>
Fetching a Variable
To retrieve a value, use apcu_fetch(). It's good practice to use the optional second parameter, $success, to distinguish between a false value stored in the cache and a cache miss.
<?php
$key = 'user:123:color';
$color = apcu_fetch($key, $success);
if ($success) {
echo "Found color: $color\n"; // Outputs: Found color: blue
} else {
echo "Cache miss for key '$key'.\n";
}
?>
Checking if a Key Exists
Before fetching, you might want to check if a key exists using apcu_exists().
<?php
$key = 'user:123:color';
if (apcu_exists($key)) {
echo "Key '$key' exists in the cache.\n";
} else {
echo "Key '$key' does not exist.\n";
}
?>
Storing Only if the Key Doesn't Exist
If you want to add an item to the cache only if it's not already there (an atomic add operation), use apcu_add().
<?php
$key = 'user:123:color';
// First attempt will succeed
if (apcu_add($key, 'green')) {
echo "Added 'green' to cache.\n";
} else {
echo "Key '$key' already exists.\n";
}
// Second attempt will fail because the key now exists
if (apcu_add($key, 'red')) {
echo "Added 'red' to cache.\n";
} else {
echo "Key '$key' already exists.\n";
}
?>
Deleting a Variable
To remove an item from the cache, use apcu_delete().
<?php
$key = 'user:123:color';
if (apcu_delete($key)) {
echo "Key '$key' has been deleted.\n";
}
// Now, it no longer exists
if (!apcu_exists($key)) {
echo "Key '$key' is gone.\n";
}
?>