Home Articles Forums Gallery Marketplace Videos

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

FeatureAPCuOPcache
Stores PHP application dataYesNo
Stores compiled PHP scriptsNoYes
Requires application codeYesNo
Uses shared memoryYesYes
Survives PHP/server restartNoNo
Useful for JSON cachingYesNo
Useful for database resultsYesNo

They complement one another rather than compete.

6. A few things to understand

There are some practical limitations:

  • APCu is not persistent storage. Never use it as the authoritative copy of important data.
  • It is generally shared between PHP processes within the same applicable PHP environment, but not across separate servers or isolated PHP environments.
  • Cache entries can be evicted when memory is exhausted.
  • APCu is not a replacement for a database.
  • Cache keys should be namespaced to avoid collisions between applications.
  • Avoid caching user-specific information under keys shared by all visitors.

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.

Leave a Comment

Licensed under CC BY-NC 4.0

Peter Martin viewpoints are those of its owner. You may share and adapt this article for non-commercial purposes, provided proper attribution is given. Attribution should include:

Title: Using APCu
Author: Peter Martin
Original URL: https://www.woodcentral.com/-/peter/using-apcu/
License: CC BY-NC 4.0

Site Index