Created
February 18, 2012 14:30
-
-
Save synboo/1859557 to your computer and use it in GitHub Desktop.
LRU (Last Recently Used) cache
This file contains 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 | |
/** | |
* 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]; | |
} | |
} |
This file contains 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 | |
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')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Good but...
If the user specifies a numeric key, it doesn't work.