A robust, production-ready caching library with automatic driver detection, fallback support, and multi-backend coordination.
- Multiple Cache Backends: Memory, Database (SQL), and Redis
- Automatic Detection: Detects available backends and falls back gracefully
- Multi-Backend Support: Write to multiple backends simultaneously for redundancy
- Configuration-Driven: Enable/disable backends without code changes
- Zero Dependencies (except optional Redis support)
- PSR-4 Compliant: Standard PHP package structure
- Comprehensive Tests: 45+ unit tests covering all scenarios
composer require ksfraser/ksf-cacheFor Redis caching, install the Predis library:
composer require predis/predisuse Ksfraser\KsfCache\CacheFactory;
// Automatically selects the best available backend
$cache = CacheFactory::create();
$cache->set('user:123', $userData, 3600);
$userData = $cache->get('user:123');$cache = CacheFactory::createMemory();
$cache->set('key', 'value');$pdo = new PDO('mysql:host=localhost;dbname=myapp', 'user', 'pass');
$cache = CacheFactory::createDatabase($pdo);
// Create the cache table (run once)
// $cache->createTable();
$cache->set('key', 'value', 3600);$cache = CacheFactory::createRedis([
'host' => 'localhost',
'port' => 6379,
]);
$cache->set('key', 'value');Coordinate multiple caches for maximum reliability:
use Ksfraser\KsfCache\CacheManager;
use Ksfraser\KsfCache\MemoryCache;
use Ksfraser\KsfCache\DatabaseCache;
$memory = new MemoryCache();
$database = new DatabaseCache($pdo);
$manager = new CacheManager(
['memory' => $memory, 'database' => $database],
[],
'memory' // Primary backend for reads
);
// Writes to both backends
$manager->set('key', 'value', 3600);
// Reads from primary (memory), falls back to database
$value = $manager->get('key');
// Control backends
$manager->disableBackend('database');
$manager->enableBackend('database');$cache = CacheFactory::create([
'preferred' => ['redis', 'database', 'memory'], // Backend priority
'pdo' => $pdo, // Database connection
'redis_options' => [
'host' => 'localhost',
'port' => 6379,
'password' => 'secret',
'database' => 0,
],
'table_name' => 'cache_entries', // Database table
]);// Set a value (with optional TTL in seconds)
$cache->set('key', 'value', 3600);
// Get a value
$value = $cache->get('key', 'default');
// Check existence
if ($cache->has('key')) { }
// Delete a key
$cache->delete('key');
// Clear all
$cache->flush();// Get multiple values
$values = $cache->getMultiple(['key1', 'key2', 'key3']);
// Set multiple values
$cache->setMultiple([
'key1' => 'value1',
'key2' => 'value2',
], 3600);// Get driver name
$driver = $cache->getDriverName(); // 'memory', 'database', 'redis', 'multi(...)'
// Check availability
if ($cache->isAvailable()) { }
// Get status (CacheManager only)
$status = $manager->getStatus();For SQL-based caching, KsfCache creates this table:
CREATE TABLE ksf_cache (
cache_key VARCHAR(255) PRIMARY KEY,
value LONGBLOB NOT NULL,
expires_at DATETIME NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX idx_expires (expires_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;| Backend | Speed | Persistent | Distributed | Dependencies |
|---|---|---|---|---|
| Memory | ⚡⚡⚡ | No | No | None |
| Database | ⚡⚡ | Yes | Yes | PDO |
| Redis | ⚡⚡⚡ | Yes | Yes | Predis |
composer install
vendor/bin/phpunit tests/- Session caching
- User data (profiles, preferences)
- API response caching
- Database query results
- Product catalogs
- Shopping cart data
- Inventory checks
- User favorites
- Temporary state
- User activity tracking
- Request throttling
- Rate limiting
All cache operations fail gracefully:
// If backend is unavailable, returns default or false
$value = $cache->get('key', $default); // Never throws
// Set operations return bool
$success = $cache->set('key', 'value');
if (!$success) {
// Log error, continue with fallback
}Contributions welcome! Please:
- Fork the repository
- Create a feature branch
- Add tests for new functionality
- Submit a pull request
MIT License - See LICENSE.md for details
Kevin Fraser - @ksfraser
- Initial release
- Memory cache implementation
- Database cache implementation
- Redis cache implementation
- Multi-backend coordination
- Comprehensive test suite