Skip to content

Instantly share code, notes, and snippets.

@m8rge
Last active February 3, 2016 07:36
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 m8rge/4107b261740834565a16 to your computer and use it in GitHub Desktop.
Save m8rge/4107b261740834565a16 to your computer and use it in GitHub Desktop.
Simple limited memory cache
<?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