Skip to content

[V6˖] Cache Conditional

Georges.L edited this page Mar 25, 2017 · 7 revisions

Sometimes you may need to use a lot of conditional statement based on a cache entry. This operation is often the same one: Checking if the cache entry exists, if it does then take the value from cache, otherwise do the nasty stuff and put it on the cache.

As of the V6 an helper is now available to make those operations easier:

Getting statistics of all instanced drivers:

<?php

/**
 * @author Khoa Bui (khoaofgod)  <[email protected]> http://www.phpfastcache.com
 * @author Georges.L (Geolim4)  <[email protected]>
 */

use phpFastCache\CacheManager;
use phpFastCache\Helper\CacheConditionalHelper as CacheConditional;
use phpFastCache\Helper\TestHelper;
use Psr\Cache\CacheItemPoolInterface;

chdir(__DIR__);
require_once __DIR__ . '/../src/autoload.php';
$testHelper = new TestHelper('Cache Promise');
$defaultDriver = (!empty($argv[ 1 ]) ? ucfirst($argv[ 1 ]) : 'Files');
$cacheInstance = CacheManager::getInstance($defaultDriver, []);
$cacheKey = 'cacheKey';
$RandomCacheValue = str_shuffle(uniqid('pfc', true));


/**
 * Missing cache item test
 */
$cacheValue = (new CacheConditional($cacheInstance))->get($cacheKey, function() use ($cacheKey, $testHelper, $RandomCacheValue){

    /**
     * Here's your database/webservice/etc stuff
     */

    return $RandomCacheValue . '-1337';
});

if($cacheValue === $RandomCacheValue . '-1337'){
    $testHelper->printPassText(sprintf('The cache promise successfully returned expected value "%s".', $cacheValue));
}else{
    $testHelper->printFailText(sprintf('The cache promise returned an unexpected value "%s".', $cacheValue));
}

⚠️ The cache conditional does not allow you to set a custom expiration time. It's relying to the default cache configuration defaultTtl. See the drivers options page for more information.

Clone this wiki locally