Overview
The Lyger Cache system provides in-memory caching with TTL support, designed to maintain persistent state across requests without external dependencies like Redis. Built using Rust FFI for high performance.Class: Lyger\Cache\Cache
Singleton cache manager with automatic expiration handling.
Getting Instance
The Cache class uses the Singleton pattern. Always use
getInstance() to get the instance.Basic Operations
put()
Stores a value in the cache with optional TTL.string
required
Cache key
mixed
required
Value to store (any serializable type)
int|null
Time to live in seconds. Uses default TTL if null.
get()
Retrieves a value from the cache.string
required
Cache key
mixed
Default value if key doesn’t exist or is expired
mixed
Cached value or default
has()
Checks if a key exists and is not expired.string
required
Cache key to check
bool
True if key exists and is not expired
forget()
Removes a key from the cache.string
required
Cache key to remove
flush()
Clears all cached data.Use
flush() carefully in production as it removes all cached data.TTL Management
setTtl()
Sets the default TTL for subsequent operations.int
required
Default TTL in seconds
Cache
Returns self for method chaining
Atomic Operations
increment()
Increments a numeric value atomically.string
required
Cache key
int
Amount to increment (default: 1)
int
New value after increment
decrement()
Decrements a numeric value atomically.string
required
Cache key
int
Amount to decrement (default: 1)
int
New value after decrement
Remember Pattern
remember()
Gets cached value or stores result of callback if not exists.string
required
Cache key
callable
required
Function to call if cache misses
int|null
Time to live in seconds
mixed
Cached or computed value
rememberForever()
Likeremember() but caches indefinitely.
string
required
Cache key
callable
required
Function to call if cache misses
mixed
Cached or computed value
Batch Operations
getMultiple()
Gets multiple values at once.array
required
Array of cache keys
mixed
Default value for missing keys
array
Associative array of key => value pairs
putMultiple()
Stores multiple key-value pairs at once.array
required
Associative array of key => value pairs
int|null
Time to live for all values
Locking
lock()
Executes a callback with a distributed lock.string
required
Lock key
callable
required
Function to execute while locked
int
Lock timeout in seconds (default: 10)
mixed
Callback result or null if lock couldn’t be acquired
- Prevent Race Conditions
- Cache Warming
- Singleton Task
Inspection
all()
Gets all non-expired cache entries.array
Array of all cached values (excludes expired entries)
count()
Gets total number of cache entries (including expired).int
Number of entries
Practical Examples
User Session Caching
Rate Limiting
Query Result Caching
API Response Caching
The Cache system automatically handles expiration. Expired entries are automatically removed when accessed via
get(), has(), or all().