PHP array-backed LRU cache with capacity
PHP
<?php
final class LruCache
{
private array $items = [];
public function __construct(private int $capacity)
{
if ($capacity < 1) throw new InvalidArgumentException('Capacity must be positive');
}
public function get(string $key): mixed
{
if (!array_key_exists($key, $this->items)) return null;
$value = $this->items[$key];
unset($this->items[$key]);
return $this->items[$key] = $value;
}
public function put(string $key, mixed $value): void
{
unset($this->items[$key]);
$this->items[$key] = $value;
while (count($this->items) > $this->capacity) unset($this->items[array_key_first($this->items)]);
}
}