-
-
Notifications
You must be signed in to change notification settings - Fork 453
[V6˖] Cache Conditional
Georges.L edited this page Nov 18, 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:
<?php
/**
* @author Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*/
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));
}
CacheConditional::get
to pass an optional Int|\DateInterval parameter:
<?php
/**
* @author Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*/
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));
$customTtl = 60;
$cacheValue = (new CacheConditional($cacheInstance))->get($cacheKey, function() use ($cacheKey, $testHelper, $RandomCacheValue){
/**
* Here's your database/webservice/etc stuff
*/
return $RandomCacheValue . '-1337';
}; $customTtl);
❓ Finally, if you need help, always check out the inevitable README.md