Skip to content

Instantly share code, notes, and snippets.

@mikemix
Last active August 21, 2022 11:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikemix/c24a52dda95f6c4b47aa9efa767cceb4 to your computer and use it in GitHub Desktop.
Save mikemix/c24a52dda95f6c4b47aa9efa767cceb4 to your computer and use it in GitHub Desktop.
<?php
declare(strict_types=1);
namespace App\Cache;
/**
* @template TCacheItem
* @template-implements LRUCacheInterface<TCacheItem>
*/
final class LRUCache implements LRUCacheInterface
{
/**
* @var array<string, TCacheItem>
*/
private array $items = [];
private int $size;
public function __construct(int $size)
{
if ($size <= 0) {
throw new InvalidArgumentException('Cache size must be greater than 0');
}
$this->size = $size;
}
/** {@inheritDoc} */
public function add(string $key, $item): void
{
// already on the list
if (isset($this->items[$key])) {
$this->items[$key] = $item;
$this->moveToFront($key);
return;
}
$this->items[$key] = $item;
// there's still room for new items
if (\count($this->items) <= $this->size) {
return;
}
// no room for new items
// remove the least used element
\reset($this->items);
unset($this->items[\key($this->items)]);
}
/** {@inheritDoc} */
public function get(string $key)
{
if (false === isset($this->items[$key])) {
return null;
}
$this->moveToFront($key);
return $this->items[$key];
}
private function moveToFront(string $key): void
{
$cachedItem = $this->items[$key];
unset($this->items[$key]);
$this->items[$key] = $cachedItem;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment