Last active
February 3, 2016 07:36
-
-
Save m8rge/4107b261740834565a16 to your computer and use it in GitHub Desktop.
Simple limited memory cache
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 | |
class InMemoryCache | |
{ | |
public $size = 10; | |
protected $cache = []; | |
/** | |
* @param string $key | |
* @param callable $obtainCallback | |
* @return mixed|null | |
*/ | |
public function get($key, $obtainCallback) | |
{ | |
if (!array_key_exists($key, $this->cache)) { | |
$this->cache[$key] = call_user_func($obtainCallback); | |
if (count($this->cache) > $this->size) { | |
reset($this->cache); | |
unset($this->cache[key($this->cache)]); | |
} | |
} | |
return $this->cache[$key]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment