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

ActiveLibrary[Caching](/categories/caching)

purpleharmonie/cache
====================

a comprehensive psr16 cache app

1.0.0(1y ago)07MITPHP

Since Aug 1Pushed 1y ago1 watchersCompare

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

READMEChangelog (1)Dependencies (2)Versions (2)Used By (0)

Purple Cache Library
====================

[](#purple-cache-library)

Overview
--------

[](#overview)

The Purple Cache Library provides a flexible caching mechanism for your application with support for various cache types including Redis, file-based, and in-memory caching. This library adheres to the PSR-16 caching interface for standardization and ease of use.

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

[](#installation)

To install the Purple Cache Library, use Composer:

```
composer require purpleharmonie/cache
```

Cache Types
-----------

[](#cache-types)

### Redis Cache

[](#redis-cache)

A cache implementation using Redis for storage.

### File Cache

[](#file-cache)

A cache implementation using the file system for storage.

### In-Memory Cache

[](#in-memory-cache)

A cache implementation using the application memory for storage.

Factory Class: `PurpleCacheFactory`
-----------------------------------

[](#factory-class-purplecachefactory)

The `PurpleCacheFactory` class is responsible for creating instances of different cache types. It provides a single method, `createCache`, which takes a cache type and an optional configuration array.

### Usage

[](#usage)

#### Create a Redis Cache

[](#create-a-redis-cache)

```
use Purple\Libs\Cache\Factory\PurpleCacheFactory;

$redisCache = PurpleCacheFactory::createCache('redis', [
    'redis' => ['host' => 'localhost', 'port' => 6379],
    'defaultTtl' => 7200,
    'maxSize' => 1000,
    'evictionPolicy' => 'LFU'
]);
```

#### Create a File Cache

[](#create-a-file-cache)

```
$fileCache = PurpleCacheFactory::createCache('file', [
    'cacheDir' => '/path/to/cache',
    'defaultTtl' => 3600,
    'maxSize' => 500,
    'evictionPolicy' => 'LRU'
]);
```

#### Create an In-Memory Cache

[](#create-an-in-memory-cache)

```
$memoryCache = PurpleCacheFactory::createCache('memory', [
    'defaultTtl' => 1800,
    'maxSize' => 200,
    'evictionPolicy' => 'LFU'
]);
```

Cache Interface
---------------

[](#cache-interface)

### PSR-16 Methods

[](#psr-16-methods)

All cache implementations (RedisCache, FileCache, InMemoryCache) adhere to the `Psr\SimpleCache\CacheInterface`. Here are the available methods:

- `get($key, $default = null)`
- `set($key, $value, $ttl = null): bool`
- `delete($key): bool`
- `clear(): bool`
- `getMultiple($keys, $default = null): iterable`
- `setMultiple($values, $ttl = null): bool`
- `deleteMultiple($keys): bool`
- `has($key): bool`

### Example: FileCache

[](#example-filecache)

The `FileCache` class provides a file-based caching mechanism.

#### Constructor

[](#constructor)

```
public function __construct(string $cacheDir, int $defaultTtl = 3600, int $maxSize = 100, string $evictionPolicy = 'LRU')
```

- **$cacheDir**: Directory where cache files will be stored.
- **$defaultTtl**: Default time-to-live (TTL) for cache items.
- **$maxSize**: Maximum number of items in the cache.
- **$evictionPolicy**: Eviction policy (`LRU` or `LFU`).

#### Methods

[](#methods)

##### get($key, $default = null)

[](#getkey-default--null)

Retrieves the value of a cache item.

##### set($key, $value, $ttl = null): bool

[](#setkey-value-ttl--null-bool)

Stores a value in the cache.

##### delete($key): bool

[](#deletekey-bool)

Deletes a cache item.

##### clear(): bool

[](#clear-bool)

Clears the entire cache.

##### getMultiple($keys, $default = null): iterable

[](#getmultiplekeys-default--null-iterable)

Retrieves multiple cache items.

##### setMultiple($values, $ttl = null): bool

[](#setmultiplevalues-ttl--null-bool)

Stores multiple values in the cache.

##### deleteMultiple($keys): bool

[](#deletemultiplekeys-bool)

Deletes multiple cache items.

##### has($key): bool

[](#haskey-bool)

Checks if a cache item exists.

##### getMetrics(): array

[](#getmetrics-array)

Returns cache metrics such as hit count, miss count, hit ratio, and item count.

Configuration
-------------

[](#configuration)

### Redis Cache Configuration

[](#redis-cache-configuration)

- `redis`: Array containing Redis connection parameters.
- `defaultTtl`: Default time-to-live for cache items.
- `maxSize`: Maximum number of items in the cache.
- `evictionPolicy`: Eviction policy (`LRU` or `LFU`).

### File Cache Configuration

[](#file-cache-configuration)

- `cacheDir`: Directory for storing cache files.
- `defaultTtl`: Default time-to-live for cache items.
- `maxSize`: Maximum number of items in the cache.
- `evictionPolicy`: Eviction policy (`LRU` or `LFU`).

### In-Memory Cache Configuration

[](#in-memory-cache-configuration)

- `defaultTtl`: Default time-to-live for cache items.
- `maxSize`: Maximum number of items in the cache.
- `evictionPolicy`: Eviction policy (`LRU` or `LFU`).

Eviction Policies
-----------------

[](#eviction-policies)

### LRU (Least Recently Used)

[](#lru-least-recently-used)

Evicts the least recently accessed items first.

### LFU (Least Frequently Used)

[](#lfu-least-frequently-used)

Evicts the least frequently accessed items first.

Metadata Management
-------------------

[](#metadata-management)

The `FileCache` class manages metadata to track cache item access and frequency. Metadata is stored in a file (`metadata.php`) within the cache directory.

### Methods

[](#methods-1)

- `loadMetadata()`: Loads metadata from the metadata file.
- `saveMetadata()`: Saves metadata to the metadata file.
- `updateMetadata(string $key, string $operation)`: Updates metadata for a cache item.

Metrics
-------

[](#metrics)

The `getMetrics()` method in each cache implementation returns an array of cache metrics:

- `hitCount`: Number of cache hits.
- `missCount`: Number of cache misses.
- `hitRatio`: Ratio of hits to total requests.
- `itemCount`: Number of items in the cache.

### Example

[](#example)

```
$metrics = $fileCache->getMetrics();
echo "Hit Count: " . $metrics['hitCount'] . "\n";
echo "Miss Count: " . $metrics['missCount'] . "\n";
echo "Hit Ratio: " . $metrics['hitRatio'] . "\n";
echo "Item Count: " . $metrics['itemCount'] . "\n";
```

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

[](#error-handling)

The library throws `InvalidArgumentException` for invalid cache keys and configurations. Ensure to handle these exceptions in your application code.

Conclusion
----------

[](#conclusion)

The Purple Cache Library provides a robust caching solution with support for Redis, file-based, and in-memory caching. By adhering to PSR-16 standards, it ensures interoperability and ease of integration with other libraries and frameworks. Configure and use the cache that best suits your application's needs and manage cache efficiently with eviction policies and metrics tracking.

###  Health Score

22

—

LowBetter than 22% of packages

Maintenance34

Infrequent updates — may be unmaintained

Popularity4

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity39

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.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

655d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/663ec7db842234e526db71ef5326b571972234eb7bf2ead3add61ceffc8c7360?d=identicon)[ohenekofi](/maintainers/ohenekofi)

---

Top Contributors

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

### Embed Badge

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

```
[![Health](https://phpackages.com/badges/purpleharmonie-cache/health.svg)](https://phpackages.com/packages/purpleharmonie-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/predis-adapter

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

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

Neos Cache Framework

102.0M31](/packages/neos-cache)[pdffiller/qless-php

PHP Bindings for qless

29113.2k1](/packages/pdffiller-qless-php)

PHPackages © 2026

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