Skip to content

Instantly share code, notes, and snippets.

@Finesse
Last active April 25, 2018 06:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Finesse/2317bcf2c8c29d24c608d1e08de2f196 to your computer and use it in GitHub Desktop.
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.
<?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