Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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