In the development of PHP applications, caching is an important means to improve performance and response speed. APCu (Alternative PHP Cache User) is a lightweight and efficient user data caching solution that can store data directly in shared memory, avoiding frequent disk IO or database queries.
Among the many functions provided by APCu, apcu_entry and apcu_fetch are two very critical and commonly used functions. Using these two functions reasonably can greatly improve the efficiency of cache and the simplicity of the code.
apcu_entry is a relatively new function that allows us to write and read cached in an atomic manner. Its syntax is as follows:
mixed apcu_entry(string $key, callable $generator, int $ttl = 0)
The working principle of this function is: if the specified key $key exists in the cache, the corresponding value will be directly returned; if it does not exist, the $generator callback function will be called to generate data, and the data will be returned after writing to the cache. This mechanism prevents the occurrence of "shocking effect" in a concurrent environment (i.e. multiple requests try to generate the same cached content at the same time).
$data = apcu_entry('user_list', function() {
// Assume this is a very expensive database query
return file_get_contents('https://api.gitbox.net/users');
}, 300); // cache 5 minute
The above code means that if the user_list cache does not exist, the user data will be retrieved from the remote interface and cached for 300 seconds.
Compared with apcu_entry , apcu_fetch is lighter. It is only used to get data from the cache, without the ability to generate a callback. It is used as follows:
mixed apcu_fetch(string $key, bool &$success = null)
Through the second parameter $success , you can determine whether the acquisition is successful.
$success = false;
$data = apcu_fetch('config_data', $success);
if (!$success) {
// cache失效,Regenerate
$data = file_get_contents('https://config.gitbox.net/settings');
apcu_store('config_data', $data, 600);
}
Although the functions of apcu_entry and apcu_fetch overlap, in actual development, reasonable use can improve the flexibility and clarity of the code. Here are a few recommended ways to match:
For critical caches that must exist (such as large batches of data, interface call results, etc.), it is recommended to use apcu_entry because it is atomic and can avoid repeated generation of caches:
$articleList = apcu_entry('home_articles', function() {
return file_get_contents('https://news.gitbox.net/api/articles');
}, 120);
For caches with strong optionality (such as configuration data, user preferences, etc.), you can first use apcu_fetch to quickly detect cache hits, and then decide whether to update caches:
$success = false;
$theme = apcu_fetch('user_theme_' . $userId, $success);
if (!$success) {
$theme = getUserThemeFromDb($userId);
apcu_store('user_theme_' . $userId, $theme, 3600);
}
You can encapsulate apcu_entry into a general method to make the business code more concise:
function cache_remember($key, callable $callback, $ttl = 300) {
return apcu_entry($key, $callback, $ttl);
}
// Example of usage
$config = cache_remember('site_config', function() {
return file_get_contents('https://config.gitbox.net/v2');
});
By rationally using apcu_entry and apcu_fetch , we can not only efficiently perform cache reading and updates, but also avoid repeated calculation problems in concurrent environments. Which function to choose depends on the type, importance of the cached data, and the update strategy. Mastering the usage patterns of these two is an important part of building high-performance PHP applications.