In highly concurrent web applications, frequent data reading and writing will become performance bottlenecks. In order to alleviate the pressure on database and speed up data access, developers often use caching mechanisms as the intermediate layer. APCu is a lightweight memory caching solution that is particularly popular in PHP. Among the many interfaces provided by APCu , the apcu_entry function has become a powerful tool for building efficient data caching strategies with its atomicity and convenience.
This article will introduce how to use the apcu_entry function and combine persistent storage (such as a database or file system) to achieve efficient and reliable data access solutions.
apcu_entry is a convenient function introduced in PHP 5.5+, which allows you to define a callback function to "backfill" the cache while getting the cache value. If there is no corresponding key in the cache, it will automatically call the callback function to generate data and write to the cache.
The function signature is as follows:
mixed apcu_entry(string $key, callable $generator, int $ttl = 0)
$key : The cached key name.
$generator : A callback function used to generate data.
$ttl : cache survival time (seconds), default is never expired.
The traditional cache usage method is "check the cache first, then the database", the process is as follows:
Query whether the cache hits.
If hit, return directly.
If it is missed, read data from the database.
Write data to cache and return.
Using apcu_entry , we can compress the above logic into one line:
$data = apcu_entry('user_42', function() {
return fetch_user_from_db(42);
}, 300);
The meaning of the above code is: try to read user_42 from the cache. If not, execute fetch_user_from_db(42) to get the data and cache it for 300 seconds.
Suppose we have a user information table and now want to cache user data:
function fetch_user_from_db($id) {
$pdo = new PDO('mysql:host=localhost;dbname=testdb', 'root', '');
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$id]);
return $stmt->fetch(PDO::FETCH_ASSOC);
}
function get_user($id) {
return apcu_entry("user_$id", function() use ($id) {
return fetch_user_from_db($id);
}, 600); // cache 10 minute
}
This mode not only has concise code, but also effectively avoids cache breakdown problems.
Some data comes from external APIs and the call costs are high. For example, get user information from https://api.gitbox.net/user/42 . We can also use apcu_entry as cache:
function fetch_user_from_api($id) {
$url = "https://api.gitbox.net/user/$id";
$response = file_get_contents($url);
return json_decode($response, true);
}
function get_user_from_api($id) {
return apcu_entry("api_user_$id", function() use ($id) {
return fetch_user_from_api($id);
}, 300); // cache 5 minute
}
This can greatly reduce the frequency of calling remote APIs and improve response speed.
Shared memory limit : APCu's cached data is stored in local memory and is shared between different PHP-FPM processes, so make sure apc.shm_size is sufficient.
Applicable to native only : APCu is an in-process cache and not for multi-server environments. Can be used in conjunction with distributed caches such as Redis, Memcached, etc.
Suitable for data with more read and less read : APCu cache is not recommended for frequently updated data, and synchronization mechanism should be used to prevent data inconsistencies.
With apcu_entry , we can gracefully combine caches with persistent storage such as databases or APIs to write concise, efficient and fault-tolerant code. Its atomicity and lazy loading characteristics not only simplify the development process, but also improve the maintainability of the system.
Whether it is cached locally in database query results or reducing the frequency of access to remote APIs, apcu_entry is a recommended practical solution. It is an indispensable part of PHP projects that pursue performance optimization.