When using PHP's APCu cache extension, developers often come into contact with the two functions: apcu_entry() and apcu_add() . They are all used to write data into the cache, but there are obvious differences in behavior and applicable scenarios. This article will analyze the differences between the two from the perspectives of implementation principles, usage scenarios and performance, and explain them in combination with actual examples.
apcu_add(string $key, mixed $var, int $ttl = 0): bool
This function adds a value to the cache, and if the specified $key already exists, the addition fails, returning false . This means that apcu_add() is a "add only once" operation, often used for initialization or scenarios that need to be avoided.
apcu_entry(string $key, callable $generator, int $ttl = 0): mixed
This function will try to get the value corresponding to $key from the cache; if the key does not exist, the $generator callback function is called to generate data and write to the cache. Its typical purpose is to "lazy load" scenarios to avoid repeated expensive operations.
Determine whether the key exists:
apcu_add() is atomic, it tries to add directly, and returns if the key already exists, avoiding read-write races.
Apcu_entry() first tries to read it, if it misses, then callback to generate data and try to write it. This may result in repeated calculations under concurrency (although the actual probability of occurrence is low).
Write behavior:
apcu_add() will never overwrite the existing value, and is suitable for situations where you only want to "set once".
apcu_entry() will automatically calculate and write when the cache does not exist, suitable for lazy loading.
Simplicity:
apcu_entry() provides a clearer encapsulation structure, and one line of code implements cache read + generation logic when invalidated, with clearer semantics.
apcu_add() requires the developer to manually write the read and judgment logic.
$config = [
'site_name' => 'GitBox',
'max_upload' => 100
];
$key = 'site_config';
if (!apcu_add($key, $config, 3600)) {
// Already exists,No treatment is done
}
Suitable for configuration data written in the deployment or initialization phase, ensuring that it is not set or overwritten repeatedly.
$data = apcu_entry('user_list', function() {
// Assume this function query the database
return file_get_contents('https://gitbox.net/api/users');
}, 600);
Here user_list gets data and caches it through the access API when it does not exist, making it ideal for frequently read but occasionally changing data.
Scene | Use apcu_add() | Use apcu_entry() |
---|---|---|
Initialize settings | ? | ? |
Avoid coverage | ? | ? |
Automatically generated | ? | ? |
Lazy loading | ? | ? |
Simplify cache logic | ? | ? |
In a high concurrency environment, although apcu_entry() is convenient, its internal logic is not strongly consistent. Multiple processes may simultaneously determine that the key does not exist and generate data. Therefore, if the callback is expensive or the result must be unique, it is recommended to add a lock mechanism or use apcu_add() to assist in judgment.
$key = 'report_2025';
if (!apcu_add($key, true, 300)) {
// The task has been executed in another process
return;
}
generateExpensiveReport(); // Just execute once
Using apcu_add() is the best choice when you want to perform a write only once;
Using apcu_entry() is a more efficient way to get and cache results from calculations automatically;
Understanding the difference will allow you to design PHP's cache logic more rationally, improve application performance and reduce resource consumption.