PHPackages                             ksfraser/ksf-cache - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Caching](/categories/caching)
4. /
5. ksfraser/ksf-cache

ActiveLibrary[Caching](/categories/caching)

ksfraser/ksf-cache
==================

Production-grade multi-backend caching system with automatic driver detection and fallback support

03↓100%PHP

Since Apr 19Pushed 1mo agoCompare

[ Source](https://github.com/ksfraser/KsfCache)[ Packagist](https://packagist.org/packages/ksfraser/ksf-cache)[ RSS](/packages/ksfraser-ksf-cache/feed)WikiDiscussions main Synced 1w ago

READMEChangelogDependenciesVersions (1)Used By (0)

KsfCache - Production-Grade Multi-Backend Caching
=================================================

[](#ksfcache---production-grade-multi-backend-caching)

[![Latest Version](https://camo.githubusercontent.com/e978b8e56c7e480f91bdcff8fd2331ee3d2cd268643948ee0fe5d263d80a4b4f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6b736672617365722f6b73662d63616368652e737667)](https://packagist.org/packages/ksfraser/ksf-cache)[![License: MIT](https://camo.githubusercontent.com/fdf2982b9f5d7489dcf44570e714e3a15fce6253e0cc6b5aa61a075aac2ff71b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d79656c6c6f772e737667)](https://opensource.org/licenses/MIT)[![PHP Version](https://camo.githubusercontent.com/cf968879a729b647e7dfa5d47f45a49672a78838d9c43c0b94bfd3a98dafdef2/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f6b736672617365722f6b73662d63616368652e737667)](https://php.net)

A robust, production-ready caching library with automatic driver detection, fallback support, and multi-backend coordination.

Features
--------

[](#features)

- **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

Installation
------------

[](#installation)

```
composer require ksfraser/ksf-cache
```

### Optional: Redis Support

[](#optional-redis-support)

For Redis caching, install the Predis library:

```
composer require predis/predis
```

Quick Start
-----------

[](#quick-start)

### Default Auto-Detection

[](#default-auto-detection)

```
use Ksfraser\KsfCache\CacheFactory;

// Automatically selects the best available backend
$cache = CacheFactory::create();

$cache->set('user:123', $userData, 3600);
$userData = $cache->get('user:123');
```

### Memory Cache (Fast, In-Process)

[](#memory-cache-fast-in-process)

```
$cache = CacheFactory::createMemory();
$cache->set('key', 'value');
```

### Database Cache (Persistent)

[](#database-cache-persistent)

```
$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);
```

### Redis Cache (Fast, Distributed)

[](#redis-cache-fast-distributed)

```
$cache = CacheFactory::createRedis([
    'host' => 'localhost',
    'port' => 6379,
]);

$cache->set('key', 'value');
```

Multi-Backend Strategy
----------------------

[](#multi-backend-strategy)

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');
```

Configuration Options
---------------------

[](#configuration-options)

```
$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
]);
```

API Reference
-------------

[](#api-reference)

### Basic Operations

[](#basic-operations)

```
// 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();
```

### Batch Operations

[](#batch-operations)

```
// Get multiple values
$values = $cache->getMultiple(['key1', 'key2', 'key3']);

// Set multiple values
$cache->setMultiple([
    'key1' => 'value1',
    'key2' => 'value2',
], 3600);
```

### Introspection

[](#introspection)

```
// Get driver name
$driver = $cache->getDriverName();  // 'memory', 'database', 'redis', 'multi(...)'

// Check availability
if ($cache->isAvailable()) { }

// Get status (CacheManager only)
$status = $manager->getStatus();
```

Database Schema
---------------

[](#database-schema)

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;
```

Performance Comparison
----------------------

[](#performance-comparison)

BackendSpeedPersistentDistributedDependenciesMemory⚡⚡⚡NoNoNoneDatabase⚡⚡YesYesPDORedis⚡⚡⚡YesYesPredisTesting
-------

[](#testing)

```
composer install
vendor/bin/phpunit tests/
```

Use Cases
---------

[](#use-cases)

### Web Applications

[](#web-applications)

- Session caching
- User data (profiles, preferences)
- API response caching
- Database query results

### E-Commerce

[](#e-commerce)

- Product catalogs
- Shopping cart data
- Inventory checks
- User favorites

### Real-Time Systems

[](#real-time-systems)

- Temporary state
- User activity tracking
- Request throttling
- Rate limiting

Error Handling
--------------

[](#error-handling)

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
}
```

Contributing
------------

[](#contributing)

Contributions welcome! Please:

1. Fork the repository
2. Create a feature branch
3. Add tests for new functionality
4. Submit a pull request

License
-------

[](#license)

MIT License - See LICENSE.md for details

Author
------

[](#author)

Kevin Fraser - [@ksfraser](https://github.com/ksfraser)

Changelog
---------

[](#changelog)

### 1.0.0

[](#100)

- Initial release
- Memory cache implementation
- Database cache implementation
- Redis cache implementation
- Multi-backend coordination
- Comprehensive test suite

###  Health Score

20

—

LowBetter than 13% of packages

Maintenance59

Moderate activity, may be stable

Popularity4

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity11

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

### Community

Maintainers

![](https://www.gravatar.com/avatar/c8870cc04b29a973eed9ad367a936ab274d744de37ff0c35fa0540a932905271?d=identicon)[ksfraser](/maintainers/ksfraser)

---

Top Contributors

[![ksfraser](https://avatars.githubusercontent.com/u/54461925?v=4)](https://github.com/ksfraser "ksfraser (5 commits)")

### Embed Badge

![Health badge](/badges/ksfraser-ksf-cache/health.svg)

```
[![Health](https://phpackages.com/badges/ksfraser-ksf-cache/health.svg)](https://phpackages.com/packages/ksfraser-ksf-cache)
```

###  Alternatives

[barryvdh/laravel-httpcache

HttpCache for Laravel

513404.4k10](/packages/barryvdh-laravel-httpcache)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
