Last active
April 25, 2018 06:21
-
-
Save Finesse/2317bcf2c8c29d24c608d1e08de2f196 to your computer and use it in GitHub Desktop.
PSR cache interfaces have the same problem: they don't consider race condition when a cache is stale and a process starts updating cache when another process is already doing it. This proposal make this problem solving be incapsulated into a cache object while keeping it simple.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$cache = new Cache(); // A cache implementation | |
/* Basic usage */ | |
/* | |
This method returns a cached value. | |
If the value needs to be recalculated, the function from the second argument is called. | |
The $cache object makes this function not to be called too often in any race conditions by setting locks, updating before expiration or any other method. | |
Arguments: | |
- cache key; | |
- value calculating function (returns the value to cache); | |
- cache life time (seconds or a DateTimeInterface object). | |
*/ | |
$value = $cache->get('keyName', function() { | |
// Do some long calculations that should be cached | |
$stuff = calculateSomethingForLongTime(); | |
return $stuff; | |
}, 3600); | |
echo "Cached value: $value."; | |
/* "Advanced" usage */ | |
$cache->delete('keyName'); | |
$cache->clean(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment