Current Location: Home> Latest Articles> How to cache JSON data and objects through apcu_entry

How to cache JSON data and objects through apcu_entry

gitbox 2025-05-18

apcu_entry is an APCu (Alternative PHP Cache) cache function provided by PHP. APCu is a user-level cache designed to cache variables in PHP scripts. By storing data in memory, APCu can effectively reduce the number of accesses to the database or file system, thereby improving performance.

The function of the apcu_entry function is to check whether there is a certain data in the cache. If it exists, the data is fetched directly from the cache; if it does not exist, the data is calculated and the result is stored in the cache. This process not only avoids repeated calculations, but also ensures the effectiveness of the cache.

The basic syntax of the apcu_entry function:

 apcu_entry(string $key, callable $callback, int $ttl = 0)
  • $key : The cached key name, used to uniquely identify cached data.

  • $callback : A closure (callback) used to calculate the cached content. The closure is executed only if the cache does not exist.

  • $ttl : The cached expiration time, in seconds (optional parameter).

Use apcu_entry to cache JSON data

JSON data is often used in PHP applications to exchange data with the front-end or stored in a database. In some cases, we need to get JSON data from an external interface and use it frequently. In order to avoid requesting external interfaces every time, we can use apcu_entry to cache JSON data into memory, reducing duplicate network requests and improving performance.

Example: Cache JSON data fetched by external API

Suppose we have an external API (such as GitHub API) and we need to get user information and cache it. Using apcu_entry can avoid frequent access to this API.

 <?php
// Define the cached key name
$key = 'github_user_data';

// use apcu_entry cache JSON data
$user_data = apcu_entry($key, function() {
    // Simulate from the outside API 获取data
    $url = 'https://api.github.com/users/octocat';
    
    // send GET Request and get JSON response
    $json_data = file_get_contents($url);
    
    // 将response转换为 PHP Array
    return json_decode($json_data, true);
}, 3600); // 设置cache 1 Hour(3600Second)

// 输出cache或获取到的data
echo 'User Name: ' . $user_data['login'] . "\n";
echo 'User Bio: ' . $user_data['bio'] . "\n";
?>

In the above example, apcu_entry checks whether GitHub user data has been cached. If the cache exists, it will directly return the cached result. If the cache does not exist, access the external API to obtain the data through the file_get_contents function, then store the data into the cache, and set the cache expiration time to 1 hour.

Notice:

  • Since apcu_entry stores cached data in memory, it is suitable for cache relatively small and frequently accessed data. For larger data sets or data that require persistence, other caching schemes (such as Redis or Memcached) are recommended.

  • apcu_entry is a memory-based cache, so its storage is temporary and the cache will expire when the PHP script ends.

Cache Objects with apcu_entry

In addition to JSON data, apcu_entry can also be used to cache PHP objects. In many scenarios, PHP objects require complex calculations or querying large amounts of data from a database. Caching these objects can greatly improve the program's response speed.

Example: The cache database query result is an object

Suppose we have a database query result that needs to be encapsulated into an object, and we can cache the object to avoid database query every time we request it.

 <?php
class User
{
    public $id;
    public $name;
    public $email;

    public function __construct($id, $name, $email)
    {
        $this->id = $id;
        $this->name = $name;
        $this->email = $email;
    }
}

// Define the cached key name
$key = 'user_data_123';

// use apcu_entry cachedata库查询结果
$user = apcu_entry($key, function() {
    // 模拟从data库获取data
    $id = 123;
    $name = 'John Doe';
    $email = '[email protected]';

    // create User Object and return
    return new User($id, $name, $email);
}, 3600); // 设置cache 1 Hour(3600Second)

// 输出cache或获取到的data
echo 'User Name: ' . $user->name . "\n";
echo 'User Email: ' . $user->email . "\n";
?>

In this example, we cache a User object using apcu_entry . Each time apcu_entry requests, apcu_entry checks whether this object already exists in the cache. If it exists, it will return the cached object directly; if the cache does not exist, it will create a new object and cache it.

Notice:

  • Objects need to be serialized before they can be stored in the cache. APCu will automatically handle the serialization and deserialization of objects, so developers do not need to operate manually.

  • After the cache expires, the new request will recalculate and cache the results.