High-performance in-memory caching with Rust FFI backend
Lyger provides a powerful in-memory caching system that persists across requests in Always-Alive mode. The cache is backed by Rust FFI for maximum performance, making it a Redis alternative without external dependencies.
use Lyger\Cache\Cache;$cache = Cache::getInstance();// Store a value with default TTL (3600 seconds)$cache->put('user:123', $userData);// Store with custom TTL$cache->put('session:abc', $sessionData, 1800); // 30 minutes// Store multiple values$cache->putMultiple([ 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3'], 600); // 10 minutes TTL
// Get a value$user = $cache->get('user:123');// Get with default value if not found$user = $cache->get('user:123', ['name' => 'Guest']);// Check if key existsif ($cache->has('user:123')) { $user = $cache->get('user:123');}// Get multiple values$values = $cache->getMultiple(['key1', 'key2', 'key3']);
For maximum performance, Lyger uses Rust FFI for cache operations when available. This provides near-native speed for cache operations.
Copy
use Lyger\Core\Engine;$engine = Engine::getInstance();// Set value (blazingly fast)$engine->cacheSet('key', 'value');// Get value$value = $engine->cacheGet('key');// Delete key$engine->cacheDelete('key');// Clear all cache$engine->cacheClear();// Get cache size$size = $engine->cacheSize();
The Rust FFI cache provides 10-100x faster performance compared to PHP arrays or file-based caching. Perfect for high-throughput applications.
$result = $cache->lock('import_users', function() { // This code runs exclusively // Only one process can execute at a time return importUsersFromAPI();}, 10); // Lock timeout: 10 secondsif ($result === null) { echo "Another process is running";}
Cache locks are simple mutex implementations. For distributed systems, use a dedicated lock service like Redis or a database-based lock.
// In bootstrap or server start$cache = Cache::getInstance();$cache->put('app_config', loadConfig());$cache->put('routes', loadRoutes());$cache->put('translations', loadTranslations());
Cache Keys
Use consistent, hierarchical naming:
Copy
// Good naming patterns$cache->put('user:123:profile', $profile);$cache->put('user:123:posts', $posts);$cache->put('api:v1:users:list', $users);// Avoid generic names$cache->put('data', $data); // Too generic$cache->put('temp', $temp); // Unclear purpose
TTL Strategy
Set appropriate TTL based on data volatility:
Copy
// Static data - long TTL$cache->put('countries', $countries, 86400); // 24 hours// Dynamic data - short TTL $cache->put('trending_posts', $posts, 300); // 5 minutes// User-specific - medium TTL$cache->put('user:123:feed', $feed, 1800); // 30 minutes