Using APCu

APCu is different from OPcache. While OPcache works automatically, APCu requires you to explicitly put data into the cache and retrieve it from your PHP application.

Think of it as a small, very fast, shared-memory key-value store for PHP.

You can use it to avoid repeatedly performing operations such as database queries, reading JSON files, generating navigation menus, or calculating frequently requested values.

1. Basic APCu operations

APCu has a relatively simple API.

Store a value:

apcu_store('site_title', 'WoodCentral', 3600);

The third argument is the expiration time in seconds. Here, the value expires after one hour.

Retrieve a value:

$title = apcu_fetch('site_title');

Check whether a value exists:

if (apcu_exists('site_title')) {
 echo 'Cache entry exists';
}

Delete a value:

apcu_delete('site_title');

Clear the entire cache:

apcu_clear_cache();

Be careful with apcu_clear_cache(): it clears the user cache for the applicable APCu environment, not just one application entry.

2. A practical example: caching a JSON file

Suppose your website reads a JSON file containing navigation links or other frequently accessed information.

Without APCu:

$data = json_decode(
 file_get_contents(__DIR__ . '/DATA/links.json'),
 true
);

Every request reads and decodes the file.

With APCu:

<?php
$file = __DIR__ . '/DATA/links.json';
$key = 'woodcentral_links';
$data = apcu_fetch($key, $success);
if (!$success) {
 $json = file_get_contents($file);
 $data = json_decode($json, true);
 if (is_array($data)) {
 apcu_store($key, $data, 3600);
 }
}

Now the JSON file is read and decoded only when the cache entry is missing or expires.

Subsequent requests retrieve the already-decoded PHP array from shared memory.

3. A reusable caching function

Rather than repeating the same logic throughout your application, you could create a small helper function.

function wc_cache(string $key, callable $callback, int $ttl = 3600): mixed
{
 if (!function_exists('apcu_fetch')) {
 return $callback();
 }
 $value = apcu_fetch($key, $success);
 if ($success) {
 return $value;
 }
 $value = $callback();
 apcu_store($key, $value, $ttl);
 return $value;
}

Usage:

$links = wc_cache('links', function () {
 return json_decode(
 file_get_contents(__DIR__ . '/DATA/links.json'),
 true
 );
});

Or for a database query:

$categories = wc_cache('categories', function () use ($pdo) {
 return $pdo->query(
 'SELECT * FROM categories ORDER BY name'
 )->fetchAll(PDO::FETCH_ASSOC);
}, 1800);

This is sometimes called a cache-aside pattern: the application checks the cache first and retrieves the original data only when necessary.

4. Cache invalidation

One important consideration is what happens when the underlying data changes.

For example, if you update links.json, the cached version won’t automatically know about the change.

You have several options:

Expiration: Let the cache entry expire naturally.

apcu_store('links', $data, 300);

Explicit invalidation: Delete the cache entry when the underlying data changes.

apcu_delete('links');

File modification time: Automatically invalidate when a file changes.

$file = __DIR__ . '/DATA/links.json';
$key = 'links_' . filemtime($file);
$links = wc_cache($key, function () use ($file) {
 return json_decode(file_get_contents($file), true);
});

The last approach is particularly useful for file-based applications.

5. APCu versus OPcache

Feature APCu OPcache
Stores PHP application data Yes No
Stores compiled PHP scripts No Yes
Requires application code Yes No
Uses shared memory Yes Yes
Survives PHP/server restart No No
Useful for JSON caching Yes No
Useful for database results Yes No

They complement one another rather than compete.

6. A few things to understand

There are some practical limitations:

You can inspect APCu’s status using:

print_r(apcu_cache_info());

And check its memory usage using:

print_r(apcu_sma_info());

As with OPcache diagnostics, don’t leave publicly accessible diagnostic scripts on a production website.

← All posts