Skip to content

Instantly share code, notes, and snippets.

@synboo
Created February 18, 2012 14:30
Show Gist options
  • Save synboo/1859557 to your computer and use it in GitHub Desktop.
Save synboo/1859557 to your computer and use it in GitHub Desktop.
LRU (Last Recently Used) cache
<?php
/**
* LRU is a system which cache data used last recently.
* see more: http://www.slideshare.net/t_wada/tddbc-exercise
*/
class LRU
{
protected $_cache = array();
protected $_cacheSize;
public function __construct($size) {
$this->_cacheSize = $size;
}
public function set($key, $value) {
$this->_cache[$key] = $value;
if (count($this->_cache) > $this->_cacheSize) {
array_shift($this->_cache);
}
}
public function get($key) {
if ( ! isset($this->_cache[$key])) {
return null;
}
// Put the value gotten to last.
$tmpValue = $this->_cache[$key];
unset($this->_cache[$key]);
$this->_cache[$key] = $tmpValue;
return $this->_cache[$key];
}
}
<?php
require('lru.php');
$cacheSize = 2;
$lru = new LRU($cacheSize);
$data = array(
'a' => 'dataA',
'b' => 'dataB',
'c' => 'dataC',
);
foreach ($data as $key => $value) {
$lru->set($key, $value);
}
var_dump($lru->get('a'));
var_dump($lru->get('b'));
$lru->set('d', 'dataD');
var_dump($lru->get('c'));
var_dump($lru->get('d'));
@ovillemain
Copy link

Good but...
If the user specifies a numeric key, it doesn't work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment