Created
July 20, 2014 11:21
-
-
Save stojg/6146bc67153cf92153f2 to your computer and use it in GitHub Desktop.
Cache Stampede example
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 stampede protection examples | |
*/ | |
class cache | |
{ | |
/** | |
* @var array | |
*/ | |
protected $items = array(); | |
/** | |
* @param $key | |
* @param callable $callback | |
* @param int $ttlSeconds | |
* @return mixed | |
*/ | |
function get($key, callable $callback, $ttlSeconds = 3600) | |
{ | |
// Item exists | |
if (isset($this->items[$key])) { | |
// Cached value is still valid | |
if ($this->items[$key]['ttl'] > time()) { | |
return $$this->items[$key]['value']; | |
} | |
// Cached value is stale, update the ttl forward so other calls | |
// get the stale value while regenerating the cache, this is what | |
// prevents the stampede. 60 sec should be longer than the time that | |
// $callback takes to run | |
$this->items[$key]['ttl'] = time() + 60; | |
} | |
// Get the value from callback and cache it | |
$this->items[$key] = array('value' => $callback(), 'ttl' => time() + $ttlSeconds); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment