Skip to content

Instantly share code, notes, and snippets.

@pschultz
Forked from synboo/lru.php
Last active August 29, 2015 14:02
Show Gist options
  • Save pschultz/117b11f1c6cec3a4599e to your computer and use it in GitHub Desktop.
Save pschultz/117b11f1c6cec3a4599e to your computer and use it in GitHub Desktop.
<?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) {
$key = "_$key";
$this->_cache[$key] = $value;
if (count($this->_cache) > $this->_cacheSize) {
array_shift($this->_cache);
}
}
public function get($key) {
$key = "_$key";
if ( ! isset($this->_cache[$key])) {
return null;
}
// Move the value to the last position in the array.
$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'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment