1. Go to this page and download the library: Download koine/delayed-cache library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
// index.php, second 10:00:00 am
$cacheKey = 'veryExpansiveCalculation';
$veryExpansiveCalculation = function () {
sleep(60);
return '42';
};
// hasItem returns true in the false time
if (!$delayedCache->hasItem($cacheKey)) {
$delayedCache->setItem($cacheKey, $veryExpansiveCalculation);
}
$answer = $delayedCache->getItem($cacheKey);
echo 'answer is: ' . $answer;
// index.php, 10:00:10 am
$cacheKey = 'veryExpansiveCalculation';
$veryExpansiveCalculation = function () {
sleep(60);
return '42';
};
// although the result is not ready yet, hasItem will return true
if (!$delayedCache->hasItem($cacheKey)) {
$delayedCache->setItem($cacheKey, $veryExpansiveCalculation);
}
// Waits 50 seconds until the building of the cache is done and then returns
// The $veryExpansiveCalculation callback will not be executed twice, unless the
// cache is cleared
$answer = $delayedCache->getItem($cacheKey);
echo 'answer is: ' . $answer;
$cacheKey = 'veryExpansiveCalculation';
$veryExpansiveCalculation = function () {
sleep(60);
return '42';
};
// if cache is not set, it will set and then return the cached value
$answer = $delayedCache->getCachedItem($cacheKey, $veryExpansiveCalculation);
echo 'answer is: ' . $answer;