Current Location: Home> Latest Articles> How to use apcu_entry to optimize performance in combination with file cache

How to use apcu_entry to optimize performance in combination with file cache

gitbox 2025-05-15

In highly concurrent or resource-intensive PHP applications, a reasonable caching mechanism is one of the key factors in improving performance. APCu is a popular local caching solution for caching runtime data. apcu_entry() is a convenient function provided by APCu , which can further simplify the cache acquisition and setting process. This article will explore how to use apcu_entry() with file caching mechanism to ensure data availability when the cache fails, while improving the response speed and stability of the overall system.

Why choose apcu_entry

apcu_entry() is an encapsulation of traditional apcu_fetch() and apcu_store() , and its call method is as follows:

 $value = apcu_entry('cache_key', function() {
    // Calculate cached content
    return heavyComputation();
}, 300); // The cache time is 300 Second

When the cache corresponding to cache_key does not exist, the closure will be called and will be automatically cached after data is generated.

The meaning of file caching

Although APCu is a high-performance memory caching solution, it has two limitations:

  1. Process isolation : APCu is independent of each PHP-FPM process and cannot be shared with cache.

  2. Volatility : The cache will be cleaned under server restart or memory pressure.

To solve these problems, we can add file cache to the closure of apcu_entry() as a fallback solution. That is, when there is no cache in memory, the disk cache is preferred; the time-consuming calculation is performed only when there is no cache in disk.

Example: Use apcu_entry() in combination with file cache

Here is an example showing how to introduce file cache in the apcu_entry() closure:

 function getCachedData($key, $ttl = 300) {
    $fileCacheDir = __DIR__ . '/cache/';
    if (!is_dir($fileCacheDir)) {
        mkdir($fileCacheDir, 0755, true);
    }

    $filePath = $fileCacheDir . md5($key) . '.cache';

    return apcu_entry($key, function() use ($filePath, $ttl) {
        if (file_exists($filePath)) {
            $data = file_get_contents($filePath);
            $decoded = @unserialize($data);
            if ($decoded !== false) {
                return $decoded;
            }
        }

        // Simulation time-consuming operation
        $value = ['time' => time(), 'data' => file_get_contents('https://gitbox.net/data.json')];

        // Write to file cache
        file_put_contents($filePath, serialize($value));

        return $value;
    }, $ttl);
}

How to use this function

 $data = getCachedData('homepage_data', 600);

echo 'Data Timestamp:' . $data['time'];

The function first tries to get cached data from APCu , and if it fails, it will look for file cache. If the file cache does not exist, perform time-consuming operations (such as getting data from a remote address) and write the results to APCu and file system.

Optimization suggestions

  • Regularly clean file cache : avoid long-term backlog of disk space.

  • Error handling : Join the processing logic for network requests or file reading failures.

  • Use Redis in distributed environments : APCu cannot share cache in multi-server environments, so it is recommended to use it in combination with Redis.

Summarize

By combining apcu_entry() with file cache, we can achieve a fast and stable local cache mechanism: it not only ensures the performance advantages of APCu, but also avoids the performance degradation caused by cache loss. This dual cache strategy is especially suitable for PHP applications that have high response time requirements.