Current Location: Home> Latest Articles> Use apcu_entry to implement fast caching in PHP projects

Use apcu_entry to implement fast caching in PHP projects

gitbox 2025-05-17

In modern PHP applications, one of the keys to improving performance is to avoid repeated costly calculations or frequent database access. At this time, the local cache mechanism comes in handy. APCu (Alternative PHP Cache User) is popular among many small to medium-sized projects as a lightweight, memory-based caching solution. This article will introduce in detail how to use the apcu_entry function to achieve efficient and elegant local caching mechanism in PHP projects.

Why choose apcu_entry ?

The PHP APCu extension provides a variety of cache functions, but apcu_entry introduced since PHP 5.5 is one of the simplest and safest ways. Its function is: if there is already a specified key in the cache, it will directly return its value; if not, the provided callback function will be executed to generate the value and stored in the cache .

Compared with the traditional apcu_fetch + judgment + apcu_store method, apcu_entry is more concise and less prone to errors.

Basic usage

 $value = apcu_entry('my_cache_key', function() {
    // Perform some time-consuming operations,For example, database query
    return getExpensiveData();
});

The above code will:

  1. Try to read the value of key as my_cache_key from the cache;

  2. If the cache hits, return directly;

  3. Otherwise, execute the callback function getExpensiveData() ;

  4. The return value is automatically stored in the cache and returns the value.

Example: Cache list of popular articles

Suppose we have a website gitbox.net that needs to display a list of popular articles on the homepage. The process of getting these articles involves complex database queries, so we want to cache the results for 10 minutes.

 $hotArticles = apcu_entry('homepage_hot_articles', function() {
    // Simulate database query
    $articles = fetchHotArticlesFromDB();

    // Set the cache time to 600 Second(10 minute)
    apcu_store('homepage_hot_articles', $articles, 600);
    return $articles;
});

Note: Although apcu_entry will automatically cache the return value, setting TTL (expiration time) is not supported. Therefore, if you need to set TTL, you still need to call apcu_store manually in the callback.

Better packaging method

To avoid repeating TTL logic, we can encapsulate a more flexible cache helper function:

 function cacheWithTTL(string $key, callable $callback, int $ttl = 300) {
    $value = apcu_fetch($key, $success);
    if ($success) {
        return $value;
    }

    $value = $callback();
    apcu_store($key, $value, $ttl);
    return $value;
}

How to use:

 $hotArticles = cacheWithTTL('homepage_hot_articles', function() {
    return fetchHotArticlesFromDB();
}, 600);

This method not only retains TTL control but also maintains logical simplicity.

Things to note

  1. Applicable only to environments other than CLI : APCu is disabled under the CLI by default and can be enabled via configuration (but is generally not recommended).

  2. Suitable for stand-alone environments : APCu is a process memory cache, and cache cannot be shared in distributed deployments of multiple servers or containers.

  3. The cache size is limited : Please adjust the apc.shm_size setting according to the actual usage to prevent frequent elimination.

summary

Through apcu_entry , PHP developers can implement local cache in the simplest way, greatly improving the response speed and performance of projects. Combining TTL control and packaging methods in appropriate scenarios can further enhance the controllability and maintainability of caches. If your project is deployed in a stand-alone or lightweight container environment, APCu is a caching option worthy of priority.