-
-
Save seeruk/6b88353c3b737e65ac2f to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
// 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; | |
} |
This file contains hidden or 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 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