Skip to content

Instantly share code, notes, and snippets.

@seeruk
Forked from lavoiesl/cacheGetDefault.php
Last active August 29, 2015 14:10
Show Gist options
  • Save seeruk/6b88353c3b737e65ac2f to your computer and use it in GitHub Desktop.
Save seeruk/6b88353c3b737e65ac2f to your computer and use it in GitHub Desktop.
<?php
// Imagine we're in class `CacheDriver`
// ...
public function save($key, Closure $callback, $ttl = 0, $stampedeTtl = null)
{
$data = $this->cache->fetch($key);
if (false !== $data) {
return $data;
}
if (null !== $stampede) {
$stampede = max((double) $stampede, 0.001); // Prevent infinite TTL
// Data is being resolved already, wait for previus request
while ('__STAMPEDE__' === $data) {
// Wait 1/20th of the stampede TTL, to give the CPU a chance
sleep($stampede / 20);
$data = $this->cache->fetch($key);
}
}
if ($data === false) {
if (null !== $stampedeTtl) {
// Acquire lock
$this->cache->save($key, '__STAMPEDE__', $stampedeTtl);
}
// Resolve the actual data from the callback
$data = $callback();
}
$this->cache->save($key, $data, $ttl);
return $data;
}
<?php
$cache = new MyChoiceOfCache();
$cacheTtl = 3600;
$stampedeTtl = 5;
$cacheDriver = new CacheDriver($cache);
$cacheDriver->save("recent_tweets", function() {
return file_get_contents("https://api.twitter.com/1.1/search/tweets.json?q=@lavoiesl");
}, 5000, 5);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment