phasync
Resource management / LruCache

Class

LruCache

A bounded in-memory cache that forgets the least recently used entries first.

Introduction#

Class synopsis#

final class LruCache implements \Countable {
    /* Methods */
    public LruCache::__construct(int $maxEntries = PHP_INT_MAX, int $maxBytes = PHP_INT_MAX)
    public LruCache::get(string $key, mixed $default = null): mixed
    public LruCache::has(string $key): bool
    public LruCache::set(string $key, mixed $value, ?float $ttl = null): bool
    public LruCache::delete(string $key): bool
    public LruCache::clear(): void
    public LruCache::count(): int
    public LruCache::bytes(): int
}

Methods#

MethodDescription
__constructCreates an empty cache.
getReturns the value stored under $key, and makes it the most recently used.
hasReturns whether there is an entry for $key, and makes it the most recently used if there is.
setStores $value under $key, making room as needed.
deleteWhether there was an entry for $key.
clearRemoves every entry.
countThe entries held, expired ones not yet dropped included.
bytesThe bytes held, when $maxBytes is set.

Examples#

Example 1
$cache = new LruCache(maxEntries: 10_000, maxBytes: 64 << 20);
$cache->set('user:42', $json, ttl: 60);
$json = $cache->get('user:42');   // null once expired or evicted

Used in#