-
-
Save pschultz/117b11f1c6cec3a4599e to your computer and use it in GitHub Desktop.
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) { | |
$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]; | |
} | |
} |
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