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

ActiveLibrary[Caching](/categories/caching)

monkeyscloud/monkeyslegion-cache
================================

High-performance cache package for MonkeysLegion Framework with multiple drivers, atomic locks, encrypted serialization, and tiered caching

2.0.0(2mo ago)11.9k↓24%7MITPHPPHP ^8.4

Since Dec 4Pushed 2mo agoCompare

[ Source](https://github.com/MonkeysCloud/MonkeysLegion-Cache)[ Packagist](https://packagist.org/packages/monkeyscloud/monkeyslegion-cache)[ RSS](/packages/monkeyscloud-monkeyslegion-cache/feed)WikiDiscussions main Synced 3d ago

READMEChangelogDependencies (7)Versions (8)Used By (7)

MonkeysLegion Cache v2
======================

[](#monkeyslegion-cache-v2)

> High-performance, attribute-driven cache package for PHP 8.4+ with multiple drivers, atomic locks, encrypted serialization, tiered caching, and stampede protection.

[![PHP](https://camo.githubusercontent.com/7ee6e059598f89d0c686b058a5524ccebefb7d5feb16eb0902fa4a11b1c564d1/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253545382e342d3838393242462e737667)](https://php.net)[![PSR-16](https://camo.githubusercontent.com/00f5210acc87df7eecba4be303e2cd177b6b8c9305bd81b96c5f9d8ce8919619/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5053522d2d31362d636f6d706c69616e742d627269676874677265656e2e737667)](https://www.php-fig.org/psr/psr-16/)[![License: MIT](https://camo.githubusercontent.com/7013272bd27ece47364536a221edb554cd69683b68a46fc0ee96881174c4214c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d626c75652e737667)](LICENSE)

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

[](#installation)

```
composer require monkeyscloud/monkeyslegion-cache:^2.0
```

Features
--------

[](#features)

FeatureDescription**6 Drivers**Array, File, Redis, Memcached, Null, Chain (L1/L2)**Pluggable Serializers**PHP, JSON, igbinary, Encrypted (libsodium)**Atomic Locks**ArrayLock, FileLock, RedisLock**Tag-Based Invalidation**O(1) version-based tag invalidation**Stampede Protection**`flexible()` with probabilistic early expiration**Typed Getters**`integer()`, `boolean()`, `float()`, `string()`, `array()`**TTL Extension**`touch()` — extend TTL without re-reading value**Cache Events**Hit, Miss, Write, Delete — readonly event VOs**PSR-16 Compliant**Full `Psr\SimpleCache\CacheInterface` conformance**PHP 8.4 Native**Property hooks, asymmetric visibility, backed enumsQuick Start
-----------

[](#quick-start)

```
use MonkeysLegion\Cache\CacheManager;

$manager = new CacheManager([
    'default' => 'file',
    'stores' => [
        'file' => [
            'driver' => 'file',
            'path'   => __DIR__ . '/cache',
        ],
        'memory' => [
            'driver' => 'array',
        ],
        'redis' => [
            'driver'   => 'redis',
            'host'     => '127.0.0.1',
            'port'     => 6379,
            'prefix'   => 'myapp',
        ],
    ],
]);

$cache = $manager->store();           // Default (file)
$redis = $manager->store('redis');    // Named store

// Basic operations
$cache->set('user.1', $userData, ttl: 3600);
$user = $cache->get('user.1');
$cache->delete('user.1');
```

Typed Getters
-------------

[](#typed-getters)

No more manual casting:

```
$count = $cache->integer('page.views');     // int
$flag  = $cache->boolean('feature.active'); // bool
$rate  = $cache->float('exchange.rate');    // float
$name  = $cache->string('user.name');       // string
$ids   = $cache->array('active.users');     // array
```

Remember &amp; Stampede Protection
----------------------------------

[](#remember--stampede-protection)

```
// Cache-aside pattern
$users = $cache->remember('users.active', 3600, function () {
    return $db->query('SELECT * FROM users WHERE active = 1');
});

// Stale-while-revalidate (prevents cache stampede)
$data = $cache->flexible(
    key:      'api.results',
    ttl:      [300, 3600],    // [stale_window, fresh_ttl]
    callback: fn() => $api->fetchExpensiveData(),
    beta:     1.5,            // Higher = more aggressive early refresh
);
```

Tags
----

[](#tags)

O(1) tag invalidation using version-based namespacing:

```
// Scoped writes
$cache->tags(['products', 'electronics'])->set('product.42', $laptop);
$cache->tags(['products', 'clothing'])->set('product.99', $shirt);

// Mass invalidation — O(1), no key scanning
$cache->tags(['electronics'])->flush();
```

Atomic Locks
------------

[](#atomic-locks)

Prevent race conditions with distributed locks:

```
$lock = $cache->lock('deploy', seconds: 30);

// Block-scoped (auto-release)
$result = $lock->get(function () {
    return deployApplication();
}, ttl: 30);

// Manual acquire/release
if ($lock->acquire()) {
    try {
        criticalSection();
    } finally {
        $lock->release();
    }
}

// Block with timeout
$lock->block(seconds: 10, callback: function () {
    return processOrder();
});
```

### Lock Backends

[](#lock-backends)

LockUse Case`ArrayLock`Testing, single-process`FileLock`Single-server production`RedisLock`Multi-server distributed (Lua-based atomic release)Chain Store (L1/L2 Tiered Caching)
----------------------------------

[](#chain-store-l1l2-tiered-caching)

```
$manager = new CacheManager([
    'default' => 'tiered',
    'stores' => [
        'l1'     => ['driver' => 'array'],      // Fast, in-process
        'l2'     => ['driver' => 'redis', ...],  // Shared, durable
        'tiered' => ['driver' => 'chain', 'stores' => ['l1', 'l2']],
    ],
]);

$cache = $manager->store(); // ChainStore
$cache->get('key'); // L1 miss → L2 hit → promoted to L1
```

Encrypted Serialization
-----------------------

[](#encrypted-serialization)

Transparent at-rest encryption for GDPR/PCI compliance:

```
$manager = new CacheManager([
    'encrypt_key' => env('CACHE_ENCRYPT_KEY'), // 32+ bytes
    'stores' => [
        'secure' => [
            'driver'    => 'redis',
            'encrypt'   => true,     // Wrap with sodium_crypto_secretbox
            'serializer' => 'json',  // Encrypt JSON payloads
        ],
    ],
]);
```

TTL Extension (touch)
---------------------

[](#ttl-extension-touch)

Extend cache TTL without re-reading the value (single round-trip on Redis):

```
// Extend session expiry
$cache->touch('session.abc123', ttl: 1800);
```

Cache Events
------------

[](#cache-events)

Readonly event value objects for telemetry/debugging:

```
use MonkeysLegion\Cache\Event\CacheEvent;
use MonkeysLegion\Cache\Event\CacheEventType;

$event = new CacheEvent(
    type:     CacheEventType::Hit,
    key:      'user.1',
    store:    'redis',
    duration: 0.35,
);

echo $event->summary; // [redis] hit: user.1 (0.35μs)
```

CacheEntry Value Object
-----------------------

[](#cacheentry-value-object)

Introspect cached data with computed properties:

```
use MonkeysLegion\Cache\CacheEntry;

$entry = new CacheEntry(
    value:     $data,
    expiresAt: time() + 3600,
    tags:      ['user', 'premium'],
);

$entry->isExpired;     // false (property hook)
$entry->remainingTtl;  // ~3600 (property hook)
$entry->age;           // 0 (property hook)
$entry->shouldRefresh(beta: 1.5); // probabilistic early refresh
```

Cache Stats
-----------

[](#cache-stats)

```
$stats = $cache->getStats();

echo $stats->hits;            // 1423
echo $stats->hitRate;         // 0.95 (property hook)
echo $stats->memoryFormatted; // "2.45 MB" (property hook)
```

Pluggable Serializers
---------------------

[](#pluggable-serializers)

SerializerBest For`PhpSerializer`Default, supports all PHP types`JsonSerializer`Scalars/arrays, zero code execution risk`IgbinarySerializer`30-50% smaller payloads (requires ext-igbinary)`EncryptedSerializer`Decorator, transparent at-rest encryption```
'stores' => [
    'json-store' => [
        'driver'     => 'redis',
        'serializer' => 'json', // or 'php', 'igbinary'
    ],
],
```

Extending with Custom Drivers
-----------------------------

[](#extending-with-custom-drivers)

```
$manager->extend('dynamodb', function (array $config) {
    return new DynamoDbStore($config);
});
```

PHP 8.4 Features Used
---------------------

[](#php-84-features-used)

- **Property hooks** — `CacheEntry`, `CacheStats`, `CacheEvent`, `TaggedCache`, `ChainStore`
- **Asymmetric visibility** — `CacheEntry`, `CacheLock`, `CacheEvent`
- **Backed enums** — `SerializerType`, `CacheEventType`, `LockState`
- **`new` in initializers** — Default `PhpSerializer()` in constructors
- **`match` expressions** — Driver/serializer resolution
- **`declare(strict_types=1)`** — Every file

Testing
-------

[](#testing)

```
php vendor/bin/phpunit --testdox
```

**98 tests, 190 assertions** — covers all stores, serializers, locks, tags, events, enums, and CacheManager.

License
-------

[](#license)

MIT © [MonkeysCloud](https://monkeys.cloud)

###  Health Score

48

—

FairBetter than 93% of packages

Maintenance84

Actively maintained with recent releases

Popularity22

Limited adoption so far

Community19

Small or concentrated contributor base

Maturity57

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 76.5% 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 ~26 days

Recently: every ~32 days

Total

6

Last Release

83d ago

Major Versions

1.0.1 → 2.0.0.x-dev2026-04-11

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/2913369?v=4)[Jorge Peraza](/maintainers/yorchperaza)[@yorchperaza](https://github.com/yorchperaza)

---

Top Contributors

[![yorchperaza](https://avatars.githubusercontent.com/u/2913369?v=4)](https://github.com/yorchperaza "yorchperaza (13 commits)")[![Copilot](https://avatars.githubusercontent.com/in/1143301?v=4)](https://github.com/Copilot "Copilot (3 commits)")[![Amanar-Marouane](https://avatars.githubusercontent.com/u/155680356?v=4)](https://github.com/Amanar-Marouane "Amanar-Marouane (1 commits)")

---

Tags

cachephpphp-library

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[laravel/framework

The Laravel Framework.

34.8k543.8M20.1k](/packages/laravel-framework)[symfony/cache

Provides extended PSR-6, PSR-16 (and tags) implementations

4.2k373.5M3.3k](/packages/symfony-cache)[cakephp/cakephp

The CakePHP framework

8.9k19.5M1.8k](/packages/cakephp-cakephp)[algolia/algoliasearch-client-php

API powering the features of Algolia.

69735.1M159](/packages/algolia-algoliasearch-client-php)[flow-php/flow

PHP ETL - Extract Transform Load - Data processing framework

85036.3k](/packages/flow-php-flow)[matomo/matomo

Matomo is the leading Free/Libre open analytics platform

21.7k38.9k](/packages/matomo-matomo)

PHPackages © 2026

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