PHPackages                             elliephp/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. elliephp/cache

ActiveLibrary[Caching](/categories/caching)

elliephp/cache
==============

Ellie PHP Simple Cache Component

1.0.2(6mo ago)171MITPHPPHP ^8.4

Since Nov 14Pushed 6mo agoCompare

[ Source](https://github.com/ElliePHP/Cache)[ Packagist](https://packagist.org/packages/elliephp/cache)[ Docs](https://github.com/elliephp/cache)[ RSS](/packages/elliephp-cache/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (4)Versions (4)Used By (1)

Ellie PHP Cache Component
=========================

[](#ellie-php-cache-component)

A lightweight, PSR-16 compliant caching library for PHP 8.4+ with support for multiple storage backends.

[![PHP Version](https://camo.githubusercontent.com/504ead6a583c68d8d62d7bfceed24e569ca613d7a36bed380281b3455b5c7b31/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253545382e342d626c7565)](https://www.php.net/)[![License](https://camo.githubusercontent.com/f8df3091bbe1149f398a5369b2c39e896766f9f6efba3477c63e9b4aa940ef14/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d677265656e)](LICENSE)

Features
--------

[](#features)

- **PSR-16 Simple Cache** compliant
- **Multiple drivers**: Redis, Valkey, SQLite, File, APCu
- **Automatic key prefixing** for namespace isolation
- **Type-safe** with full PHP 8.4 type declarations
- **Zero configuration** defaults for quick setup
- **Garbage collection** for file-based caches
- **Batch operations** for improved performance

Requirements
------------

[](#requirements)

- PHP 8.4 or higher
- PDO extension (for SQLite driver)
- APCu extension (optional, for APCu driver)
- Redis/Valkey server (optional, for Redis driver)

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

[](#installation)

```
composer require elliephp/cache
```

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

[](#quick-start)

```
use ElliePHP\Components\Cache\CacheFactory;
use ElliePHP\Components\Cache\Cache;

// Create a file-based cache
$driver = CacheFactory::createFileDriver([
    'path' => '/path/to/cache'
]);

$cache = new Cache($driver);

// Store a value
$cache->set('user:123', 'John Doe', 3600);

// Retrieve a value
$name = $cache->get('user:123'); // "John Doe"

// Check if exists
if ($cache->has('user:123')) {
    // ...
}

// Delete a value
$cache->delete('user:123');

// Clear all cache
$cache->clear();
```

Drivers
-------

[](#drivers)

### File Driver

[](#file-driver)

Stores cache data as JSON files on the filesystem.

```
$driver = CacheFactory::createFileDriver([
    'path' => '/path/to/cache',
    'create_directory' => true,      // Auto-create directory
    'directory_permissions' => 0755  // Directory permissions
]);

$cache = new Cache($driver);
```

**Garbage Collection:**

```
// Clear expired cache files
$deletedCount = $driver->clearExpired();
```

### Redis Driver

[](#redis-driver)

Uses Redis or Valkey for high-performance caching.

```
$driver = CacheFactory::createRedisDriver([
    'host' => '127.0.0.1',
    'port' => 6379,
    'password' => null,      // Optional
    'database' => 0,         // Redis database number
    'timeout' => 5.0,        // Connection timeout
    'prefix' => 'myapp:'     // Optional key prefix
]);

$cache = new Cache($driver);
```

### SQLite Driver

[](#sqlite-driver)

Stores cache in a SQLite database file.

```
$driver = CacheFactory::createSQLiteDriver([
    'path' => '/path/to/cache.db',
    'create_directory' => true,
    'directory_permissions' => 0755
]);

$cache = new Cache($driver);
```

**Garbage Collection:**

```
// Clear expired cache entries
$deletedCount = $driver->clearExpired();
```

### APCu Driver

[](#apcu-driver)

Uses PHP's APCu extension for in-memory caching.

```
$driver = CacheFactory::createApcuDriver();
$cache = new Cache($driver);
```

Usage
-----

[](#usage)

### Basic Operations

[](#basic-operations)

```
// Set with TTL (in seconds)
$cache->set('key', 'value', 3600);

// Set without expiry (forever)
$cache->set('key', 'value', null);
$cache->set('key', 'value', 0);

// Get with default value
$value = $cache->get('key', 'default');

// Check existence
if ($cache->has('key')) {
    // Key exists and is not expired
}

// Delete
$cache->delete('key');

// Clear all
$cache->clear();
```

### Batch Operations

[](#batch-operations)

```
// Get multiple values
$values = $cache->getMultiple(['user:1', 'user:2', 'user:3'], 'default');
// Returns: ['user:1' => 'John', 'user:2' => 'Jane', 'user:3' => 'default']

// Set multiple values
$cache->setMultiple([
    'user:1' => 'John',
    'user:2' => 'Jane',
    'user:3' => 'Bob'
], 3600);

// Delete multiple values
$cache->deleteMultiple(['user:1', 'user:2', 'user:3']);
```

### TTL with DateInterval

[](#ttl-with-dateinterval)

```
use DateInterval;

// Cache for 1 hour
$cache->set('key', 'value', new DateInterval('PT1H'));

// Cache for 1 day
$cache->set('key', 'value', new DateInterval('P1D'));

// Cache for 30 days
$cache->set('key', 'value', new DateInterval('P30D'));
```

### Cache Statistics

[](#cache-statistics)

```
// Get total number of cached items
$count = $cache->count();

// Get total cache size in bytes
$size = $cache->size();
```

Key Prefixing
-------------

[](#key-prefixing)

All cache keys are automatically prefixed with `ellie_cache:` to prevent collisions. You don't need to worry about this - it's handled transparently.

```
$cache->set('user', 'John');
// Actual key stored: "ellie_cache:user"

$cache->get('user');
// Retrieves: "ellie_cache:user"
```

Key Validation
--------------

[](#key-validation)

Keys are validated according to PSR-16 specifications:

- Cannot be empty
- Maximum 255 characters
- Cannot contain: `{}()/\@:`

```
try {
    $cache->set('invalid{key}', 'value');
} catch (\ElliePHP\Components\Cache\Exceptions\InvalidArgumentException $e) {
    // Handle invalid key
}
```

Factory Method
--------------

[](#factory-method)

Use the factory for dynamic driver selection:

```
use ElliePHP\Components\Cache\CacheFactory;
use ElliePHP\Components\Cache\CacheDrivers;

$driver = CacheFactory::create(CacheDrivers::REDIS, [
    'host' => '127.0.0.1',
    'port' => 6379
]);

// Or use string
$driver = CacheFactory::create('redis', [
    'host' => '127.0.0.1'
]);
```

Available driver constants:

- `CacheDrivers::REDIS` - Redis driver
- `CacheDrivers::VALKEY` - Valkey (Redis-compatible)
- `CacheDrivers::SQLITE` - SQLite driver
- `CacheDrivers::FILE` - File driver
- `CacheDrivers::APCU` - APCu driver

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

[](#error-handling)

```
use ElliePHP\Components\Cache\Exceptions\CacheException;
use ElliePHP\Components\Cache\Exceptions\InvalidArgumentException;

try {
    $driver = CacheFactory::createRedisDriver([
        'host' => 'invalid-host'
    ]);
} catch (CacheException $e) {
    // Handle connection errors
    echo "Cache error: " . $e->getMessage();
}

try {
    $cache->set('', 'value');
} catch (InvalidArgumentException $e) {
    // Handle invalid key
    echo "Invalid key: " . $e->getMessage();
}
```

Best Practices
--------------

[](#best-practices)

### 1. Use Appropriate Drivers

[](#1-use-appropriate-drivers)

- **APCu**: Best for single-server setups, fastest performance
- **Redis/Valkey**: Best for distributed systems, shared cache
- **SQLite**: Good for moderate traffic, persistent cache
- **File**: Good for development, simple deployments

### 2. Set Reasonable TTLs

[](#2-set-reasonable-ttls)

```
// Short-lived data (5 minutes)
$cache->set('api:rate-limit', $data, 300);

// Medium-lived data (1 hour)
$cache->set('user:session', $data, 3600);

// Long-lived data (1 day)
$cache->set('config:settings', $data, 86400);

// Permanent data (until manually deleted)
$cache->set('app:version', $data, null);
```

### 3. Use Batch Operations

[](#3-use-batch-operations)

```
// Instead of multiple get() calls
$user1 = $cache->get('user:1');
$user2 = $cache->get('user:2');
$user3 = $cache->get('user:3');

// Use getMultiple()
$users = $cache->getMultiple(['user:1', 'user:2', 'user:3']);
```

### 4. Handle Cache Misses

[](#4-handle-cache-misses)

```
$data = $cache->get('expensive:data');

if ($data === null) {
    // Cache miss - fetch from source
    $data = $this->fetchExpensiveData();

    // Store in cache
    $cache->set('expensive:data', $data, 3600);
}

return $data;
```

### 5. Regular Garbage Collection

[](#5-regular-garbage-collection)

For file and SQLite drivers, schedule periodic cleanup:

```
// In a cron job or scheduled task
$driver->clearExpired();
```

Performance Tips
----------------

[](#performance-tips)

1. **Use Redis for high-traffic applications** - It's the fastest for concurrent access
2. **Batch operations** - Use `getMultiple()` and `setMultiple()` when possible
3. **Set appropriate TTLs** - Don't cache forever unless necessary
4. **Monitor cache size** - Use `$cache->size()` to track growth
5. **Use key prefixes** - The built-in prefix prevents collisions

Testing
-------

[](#testing)

```
# Run tests
composer test

# Run tests with coverage
composer test:coverage
```

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

[](#contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

License
-------

[](#license)

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

Support
-------

[](#support)

- **Issues**: [GitHub Issues](https://github.com/elliephp/cache/issues)
- **Source**: [GitHub Repository](https://github.com/elliephp/cache)

Credits
-------

[](#credits)

Created by [Joey Boli](mailto:bankuboy@proton.me)

Changelog
---------

[](#changelog)

See [IMPROVEMENTS.md](IMPROVEMENTS.md) for recent improvements and changes.

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance68

Regular maintenance activity

Popularity6

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity54

Maturing project, gaining track record

 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.

###  Release Activity

Cadence

Every ~0 days

Total

3

Last Release

185d ago

### Community

Maintainers

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

---

Top Contributors

[![joeyboli](https://avatars.githubusercontent.com/u/43940776?v=4)](https://github.com/joeyboli "joeyboli (8 commits)")

---

Tags

cacheelliephp

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[laminas/laminas-cache

Caching implementation with a variety of storage options, as well as codified caching strategies for callbacks, classes, and output

1076.9M130](/packages/laminas-laminas-cache)[cache/adapter-common

Common classes for PSR-6 adapters

11124.4M38](/packages/cache-adapter-common)[cache/filesystem-adapter

A PSR-6 cache implementation using filesystem. This implementation supports tags

705.8M82](/packages/cache-filesystem-adapter)[cache/array-adapter

A PSR-6 cache implementation using a php array. This implementation supports tags

548.3M151](/packages/cache-array-adapter)[cache/predis-adapter

A PSR-6 cache implementation using Redis (Predis). This implementation supports tags

272.6M13](/packages/cache-predis-adapter)[cache/redis-adapter

A PSR-6 cache implementation using Redis (PhpRedis). This implementation supports tags

523.9M27](/packages/cache-redis-adapter)

PHPackages © 2026

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