Current Location: Home> Latest Articles> How to elegantly clean the apcu_entry cache in PHP code

How to elegantly clean the apcu_entry cache in PHP code

gitbox 2025-05-26

In highly concurrent PHP applications, rational use of cache is an important means to improve performance and reduce database pressure. APCu (Alternative PHP Cache User) is a lightweight local cache solution suitable for fast data access in stand-alone environments. The apcu_entry function is a very practical and advanced interface in APCu. It can elegantly implement the "read cache, write and return if it does not exist". This article will introduce in detail how to use apcu_entry to manage caches, improve application performance, and attach practical example code.

1. What is apcu_entry ?

apcu_entry is a function provided by the APCu extension in PHP 5.5 and above. Its basic usage is as follows:

 mixed apcu_entry(string $key, callable $generator [, int $ttl = 0 ])

Parameter description:

  • $key : The cached key name.

  • $generator : A callback function executed when this key does not exist in the cache, its return value will be stored in the cache and returned.

  • $ttl : The cached survival time (seconds), default is 0 to mean permanent.

This pattern is called cache stampede protection , which prevents multiple processes from simultaneously discovering cache failure and requesting the underlying data source.

2. Use scenario analysis

Imagine a typical scenario: your website homepage needs to display a list of hot-selling products, and this part of the data is queried from the database. If you directly check the library for each request, it will obviously cause unnecessary performance losses. We can use apcu_entry to cache this data gracefully:

 $hotProducts = apcu_entry('hot_products', function() {
    // Simulate reading list of hot-selling products from the database
    return getHotProductsFromDatabase();
}, 300); // cache 5 minute

In this way, when the cache exists, the cache data is directly returned; otherwise, a callback is executed to read the data from the database and write to the cache.

3. Elegantly clean cache

In actual business, cached content is not static. For example, when new products are added to the hot-selling list or the product status changes, the relevant cache needs to be cleaned.

You can delete the specified cache by actively calling apcu_delete() :

 apcu_delete('hot_products');

The next time you access the next time, apcu_entry will call the generator function to update the cache. This method is clearer and atomic than the traditional apcu_fetch + apcu_store , and also avoids the "check-reset" race condition problem.

4. Application practice: User information caching example

The following is an application example combining URLs. We simulate getting user information from a remote interface (such as https://gitbox.net/api/user/123 ) and cache it:

 function getUserInfo($userId) {
    $cacheKey = "user_info_$userId";
    return apcu_entry($cacheKey, function() use ($userId) {
        // Simulate to obtain data from a remote interface
        $url = "https://gitbox.net/api/user/$userId";
        $json = file_get_contents($url);
        return json_decode($json, true);
    }, 600); // cache 10 minute
}

$user = getUserInfo(123);

If the interface data changes, you can call:

 apcu_delete("user_info_123");

to clear the information cache of specific users.

5. Performance improvement comparison

Compared with traditional cache acquisition and write logic:

 if (!apcu_exists($key)) {
    $value = expensiveOperation();
    apcu_store($key, $value);
} else {
    $value = apcu_fetch($key);
}

Using apcu_entry can significantly reduce code complexity, while also having better atomicity and concurrency performance. This is especially important in high traffic environments.

6. Summary

apcu_entry is a very powerful and easy-to-use function in APCu. It integrates data generation, cache writing, and cache reading, avoiding redundancy and competitive problems in traditional cache logic. Combined with apcu_delete , caches can be managed and cleaned gracefully, making PHP applications more efficient and stable. By using apcu_entry properly, you can easily build a faster responsive and lower loaded web system.