This is my implementation of LRU caching in PHP.
It works fine when I tested as. What are the things that I miss or need attention?
<?php
class Cache{
private $cache;
private $size;
public function __construct($size)
{
$this->cache = [];
$this->size = $size;
}
public function put($item)
{
if($this->isFull())
{
if(in_array($item, $this->cache))
{
$this->cache = array_diff($this->cache, [$item]);
}
else
{
array_pop($this->cache);
}
}
array_unshift($this->cache,$item);
}
public function display()
{
var_dump($this->cache);
}
private function isFull()
{
if(count($this->cache) >= $this->size)
{
return true;
}
}
}
$cache_size = 4;
$entries = [3,4,4,5,6,7,4,4,3,5,2,3,1,1,4];
$cache = new Cache($cache_size);
$cache->display();
foreach($entries as $entry)
{
$cache->put($entry);
}
$cache->display();
Output for above provided data
//blank cache
array(0) {
}
//insertion of all entries
array(4) {
[0]=>
int(4)
[1]=>
int(1)
[2]=>
int(3)
[3]=>
int(2)
}
!is_full()
, the $item has to be removed, if it is in_array(). \$\endgroup\$ – Holger Oct 1 '18 at 14:09