How can the issue of skipping cache blocks if the cache key exists be elegantly solved in PHP?

Issue: When caching data in PHP, it is common to check if a cache key exists before fetching the data from the cache. However, if the cache key exists, it may lead to skipping the cache blocks and directly returning the data, which defeats the purpose of caching. One elegant solution is to store a flag along with the cached data to indicate whether the data is fresh or not.

// Check if the cache key exists and if the data is fresh
if ($cache->has('my_data_key')) {
    $cachedData = $cache->get('my_data_key');
    
    if ($cachedData['is_fresh']) {
        // Use the cached data
        $data = $cachedData['data'];
    } else {
        // Fetch fresh data and update the cache
        $data = fetchDataFromSource();
        $cache->set('my_data_key', ['data' => $data, 'is_fresh' => true]);
    }
} else {
    // Fetch fresh data and store it in the cache
    $data = fetchDataFromSource();
    $cache->set('my_data_key', ['data' => $data, 'is_fresh' => true]);
}