phpFastCache
GitHub Overview
PHPSocialNetwork/phpfastcache
A high-performance backend cache system. It is intended for use in speeding up dynamic web applications by alleviating database load. Well implemented, it can drops the database load to almost nothing, yielding faster page load times for users, better resource utilization. It is simple yet powerful.
Topics
Star History
Cache Library
phpFastCache
Overview
phpFastCache is a high-performance backend cache system for PHP designed to alleviate database load in dynamic web applications, resulting in faster page load times and better resource utilization. It supports multiple storage drivers including Files, Redis, Memcache, and APCu, providing a unified API that complies with PSR-6 and PSR-16 standards.
Details
phpFastCache features a simple yet powerful design that can reduce database load to almost nothing when properly implemented. It manages multiple cache backends through a unified interface, providing consistent operation from development to production environments.
Key technical features:
- Multi-driver support: Files, Redis, Memcache, APCu, SQLite, etc.
- PSR-6/PSR-16 compliance: PHP standard cache interfaces
- Event system: Custom event handling for cache operations
- Tag functionality: Batch operations for related cache entries
- TTL/Eviction: Flexible expiration management
- Cluster support: Distributed caching with RedisArray
Pros and Cons
Pros
- Unified API: Operate multiple backends with the same interface
- High performance: Significantly reduces database load with proper implementation
- PSR compliance: Compatible with PHP standards
- Rich features: Tags, events, TTL, cluster support
- Easy installation: Simple installation via Composer
- Flexible configuration: Choose drivers based on environment
- Production proven: Extensive track record in production environments
Cons
- PHP-only: Not available for other languages
- Learning curve: Advanced features require understanding
- Driver dependency: Subject to constraints of chosen backend
- Memory usage: PHP runtime memory overhead
- Configuration complexity: Complex setup for cluster configurations
- Version migration: Breaking changes between major versions
Reference Links
Usage Examples
Basic Cache Usage
<?php
use Phpfastcache\CacheManager;
use Phpfastcache\Config\ConfigurationOption;
// Basic configuration
CacheManager::setDefaultConfig(new ConfigurationOption([
'path' => '/var/www/cache', // Path for Files driver
]));
// Get cache instance
$InstanceCache = CacheManager::getInstance('files');
// Cache key
$key = "product_list";
$CachedString = $InstanceCache->getItem($key);
// Data preparation
$products = [
'Product 1',
'Product 2',
'Product 3'
];
if (!$CachedString->isHit()) {
// No data in cache
$CachedString->set($products)
->expiresAfter(300); // Valid for 5 minutes
$InstanceCache->save($CachedString);
echo 'Data saved to cache<br>';
} else {
// Get data from cache
echo 'Data retrieved from cache<br>';
}
// Display data
$cachedData = $CachedString->get();
echo implode('<br>', $cachedData);
?>
PSR-16 Adapter Usage
<?php
use Phpfastcache\Helper\Psr16Adapter;
// PSR-16 compliant simple API
$defaultDriver = 'Files';
$Psr16Adapter = new Psr16Adapter($defaultDriver);
if (!$Psr16Adapter->has('user_settings')) {
// Set data (valid for 5 minutes)
$settings = [
'theme' => 'dark',
'language' => 'en',
'notifications' => true
];
$Psr16Adapter->set('user_settings', $settings, 300);
} else {
// Get data
$settings = $Psr16Adapter->get('user_settings');
print_r($settings);
}
?>
Multiple Driver Usage
<?php
use Phpfastcache\CacheManager;
use Phpfastcache\Config\ConfigurationOption;
// File cache configuration
$fileCache = CacheManager::getInstance('Files', new ConfigurationOption([
'path' => '/tmp/phpfastcache'
]));
// Redis cache configuration
$redisCache = CacheManager::getInstance('Redis', new ConfigurationOption([
'host' => '127.0.0.1',
'port' => 6379,
'password' => 'your_password'
]));
// APCu cache (for fast access)
$apcuCache = CacheManager::getInstance('Apcu');
// Use cases by purpose
// 1. Session data (fast access)
$sessionItem = $apcuCache->getItem('user_session_123');
if (!$sessionItem->isHit()) {
$sessionItem->set(['user_id' => 123, 'role' => 'admin']);
$apcuCache->save($sessionItem);
}
// 2. Complex query results (persistence)
$queryItem = $redisCache->getItem('complex_query_result');
if (!$queryItem->isHit()) {
$queryItem->set(expensive_database_query())
->expiresAfter(3600); // 1 hour
$redisCache->save($queryItem);
}
// 3. Images/files (filesystem)
$imageItem = $fileCache->getItem('processed_image_thumbnail');
if (!$imageItem->isHit()) {
$imageItem->set(generate_thumbnail())
->expiresAfter(86400); // 24 hours
$fileCache->save($imageItem);
}
?>
Event System Usage
<?php
use Phpfastcache\EventManager;
use Phpfastcache\CacheManager;
// Event listener for cache access
EventManager::getInstance()->onCacheGetItem(function($itemPool, $item) {
// Debug info or logging
error_log("Cache access: " . $item->getKey());
// Data modification (e.g., add prefix)
if ($item->isHit()) {
$item->set('[CACHED] ' . $item->get());
}
}, 'debug_listener');
// Event for cache save
EventManager::getInstance()->onCacheSaveItem(function($itemPool, $item) {
error_log("Cache save: " . $item->getKey() . " = " . strlen($item->get()) . " bytes");
}, 'save_logger');
$cache = CacheManager::getInstance('Files');
// Normal cache operations (events fire automatically)
$item = $cache->getItem('test_key');
if (!$item->isHit()) {
$item->set('Test data');
$cache->save($item);
}
// Remove event listener
EventManager::getInstance()->unbindEventCallback('onCacheGetItem', 'debug_listener');
?>
Tag-based Cache Management
<?php
use Phpfastcache\CacheManager;
$cache = CacheManager::getInstance('Redis');
// Create tagged cache items
$userItem = $cache->getItem('user_profile_123');
$userItem->set(['name' => 'John Doe', 'email' => '[email protected]'])
->expiresAfter(3600)
->addTag('user')
->addTag('profile');
$cache->save($userItem);
// Another user profile
$userItem2 = $cache->getItem('user_profile_456');
$userItem2->set(['name' => 'Jane Smith', 'email' => '[email protected]'])
->expiresAfter(3600)
->addTag('user')
->addTag('profile');
$cache->save($userItem2);
// Product data
$productItem = $cache->getItem('product_789');
$productItem->set(['name' => 'Laptop', 'price' => 999])
->expiresAfter(7200)
->addTag('product')
->addTag('electronics');
$cache->save($productItem);
// Batch deletion by tag
// Delete all user-related cache
$cache->deleteItemsByTag('user');
// Delete cache matching multiple tags
$cache->deleteItemsByTagsAll(['product', 'electronics']);
// Get cache items by tag
$userItems = $cache->getItemsByTag('profile');
foreach ($userItems as $item) {
echo "Cache key: " . $item->getKey() . "\n";
}
?>
Advanced Configuration and Cluster Setup
<?php
use Phpfastcache\CacheManager;
use Phpfastcache\Drivers\Redis\Config as RedisConfig;
// Redis cluster configuration
$config = new RedisConfig([
'host' => '127.0.0.1',
'port' => 6379,
'password' => 'secure_password',
'database' => 1,
'timeout' => 5,
'read_timeout' => 3,
// Compression settings
'compression' => true,
// Persistent connection
'persistent' => true,
// Security settings
'secure_file_manipulation' => true
]);
$cache = CacheManager::getInstance('Redis', $config, 'cluster_primary');
// Advanced cache operations
$complexItem = $cache->getItem('analytics_data');
if (!$complexItem->isHit()) {
// Simulate heavy processing
$analytics = [
'page_views' => 15234,
'unique_visitors' => 8456,
'bounce_rate' => 0.34,
'generated_at' => date('Y-m-d H:i:s')
];
$complexItem->set($analytics)
->expiresAfter(1800) // 30 minutes
->addTag('analytics')
->addTag('dashboard');
$cache->save($complexItem);
echo "Analytics data saved to cache\n";
} else {
$analytics = $complexItem->get();
echo "Analytics data retrieved from cache\n";
echo "Generated at: " . $analytics['generated_at'] . "\n";
}
// Cache statistics
$stats = $cache->getStats();
echo "Cache statistics:\n";
echo "- Hits: " . $stats->getHits() . "\n";
echo "- Misses: " . $stats->getMisses() . "\n";
echo "- Data size: " . $stats->getSize() . " bytes\n";
?>
Configuration File Management
<?php
// config/cache.php
return [
'default_driver' => 'redis',
'drivers' => [
'files' => [
'driver' => 'Files',
'path' => '/var/cache/phpfastcache',
'secure_file_manipulation' => true
],
'redis' => [
'driver' => 'Redis',
'host' => $_ENV['REDIS_HOST'] ?? '127.0.0.1',
'port' => $_ENV['REDIS_PORT'] ?? 6379,
'password' => $_ENV['REDIS_PASSWORD'] ?? null,
'database' => $_ENV['REDIS_DB'] ?? 0
],
'memcached' => [
'driver' => 'Memcached',
'servers' => [
['127.0.0.1', 11211, 100]
]
]
]
];
// Cache manager
class CacheService {
private static $instances = [];
private static $config;
public static function init($configPath) {
self::$config = require $configPath;
}
public static function getInstance($driver = null) {
$driver = $driver ?: self::$config['default_driver'];
if (!isset(self::$instances[$driver])) {
$config = self::$config['drivers'][$driver];
$driverName = $config['driver'];
unset($config['driver']);
self::$instances[$driver] = CacheManager::getInstance(
$driverName,
new ConfigurationOption($config)
);
}
return self::$instances[$driver];
}
}
// Usage example
CacheService::init(__DIR__ . '/config/cache.php');
$cache = CacheService::getInstance(); // Default driver
$fileCache = CacheService::getInstance('files'); // File driver
?>