Class
LruCache
A bounded in-memory cache that forgets the least recently used entries first.
Introduction#
- Reading an entry (get(), has()) makes it the most recently used; setting one does too.
- Past $maxEntries entries, or $maxBytes bytes, the least recently used go first. The bytes are those of each key and of string values; other values count their key only.
- An entry with a TTL is gone after that many seconds, by the monotonic clock. Expired entries are dropped when read, and otherwise evicted as the least recently used.
- Every operation is O(1): the entries are one PHP array in the order of their last use.
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#
| Method | Description |
|---|---|
__construct | Creates an empty cache. |
get | Returns the value stored under $key, and makes it the most recently used. |
has | Returns whether there is an entry for $key, and makes it the most recently used if there is. |
set | Stores $value under $key, making room as needed. |
delete | Whether there was an entry for $key. |
clear | Removes every entry. |
count | The entries held, expired ones not yet dropped included. |
bytes | The bytes held, when $maxBytes is set. |
Examples#
$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 evictedUsed in#
- Caching: memoizationA cache of a pure function can be shared by every request, if it is bounded.