php LRU 算法

php LRU 算法

class LRUDict
{
    protected $capacity;
    protected $items = [];

    public function __construct ($capacity)
    {
        $this->capacity = $capacity;
    }

    public function setItem(string $key,$value)
    {
        if ( isset($this->items[$key]) )
        {
            unset($this->items[$key]);
            $this->items[$key] = $value;
        }elseif (count($this->items) < $this->capacity )
        {
            $this->items[$key] = $value;
        }else
        {
            //最近没用过的,都在前面
            reset($this->items);
            $first_key = key($this->items);
            unset($this->items[$first_key]);

            $this->items[$key] = $value;
        }
    }

    public function getItem(string $key)
    {
        if (!isset($this->items[$key]))
        {
            return false;
        }
        $value = $this->items[$key];

        //用过了,放后面
        unset($this->items[$key]);
        $this->items[$key] = $value;

        return $value;
    }

    public function __toString()
    {
        return json_encode($this->items);
    }
}

测试

$d = new LRUDict(10);

foreach (range(1,15) as $i)
{
    $d->setItem($i,$i);
}

echo $d;
//结果:{"6":6,"7":7,"8":8,"9":9,"10":10,"11":11,"12":12,"13":13,"14":14,"15":15}

留下回复