lru

Fixed-capacity LRU cache with hit/miss statistics and optional TTL expiration.

v1.0.0Data structuresbundledimport "lru";
Overview Installation Documentation Examples

Overview

Fixed-capacity Least Recently Used (LRU) cache for HolyPHP with hit/miss statistics and optional per-key TTL expiration.

bundled — works offline cache ttl eviction

Quick start

import "lru";

$cache = lru_create(2);

$cache->set("a", "alpha");
$cache->set("b", "beta");

// Access "a" so it becomes the most recently used key
println($cache->get("a")); // "alpha"

// Adding "c" evicts the least recently used key ("b")
$cache->set("c", "gamma");

println($cache->has("b")); // false
println($cache->keys());   // ["c", "a"]

// Set a key with a 60-second TTL
$cache->set("session", ["user" => "alice"], 60);

// Inspect cache statistics
$stats = $cache->stats();
println($stats["hits"]);     // 1
println($stats["misses"]);   // 0
println($stats["hit_rate"]); // 1.0

Installation

In a project

Inside a project (a folder with hphp.yaml, see Projects & packages):

hphp install lru

This adds the library to hphp.yaml, installs it into .hphp/packages/lru/ and pins the exact version in hphp.lock:

require:
  lru: "^1.0"

Use it

import "lru";

lru is bundled with the compiler, so import "lru"; also works in a single file without installing anything, and hphp install works offline.

Outside a project

hphp install lru          # for your user, shared by all scripts
hphp create myapp                 # or start a project, then: hphp install lru
Packagelru
Version1.0.0 (follows the compiler)
Entry filelru.hphp
Sourcepackages/lib/lru ↗

Documentation

API Reference

Helper Function

LruCache Class

Constructor

Core Operations

Inspection & Statistics

Error Handling

All invalid inputs throw Exception with clear, prefixed messages:

Examples

01Quick start

Bundled with the compiler — import "lru"; works offline in any file, or add it to a project with hphp install lru.

import "lru";

$cache = lru_create(2);

$cache->set("a", "alpha");
$cache->set("b", "beta");

// Access "a" so it becomes the most recently used key
println($cache->get("a")); // "alpha"

// Adding "c" evicts the least recently used key ("b")
$cache->set("c", "gamma");

println($cache->has("b")); // false
println($cache->keys());   // ["c", "a"]

// Set a key with a 60-second TTL
$cache->set("session", ["user" => "alice"], 60);

// Inspect cache statistics
$stats = $cache->stats();
println($stats["hits"]);     // 1
println($stats["misses"]);   // 0
println($stats["hit_rate"]); // 1.0
Try it
hphp install lru
hphp run main.hphp

Covered by the official test suite in tests/positive/lib_lru.hphp.