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

Cache package for MonkeysLegion Framework with multiple drivers support

1.0.1(2mo ago)1885↑142.9%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 1mo ago

READMEChangelogDependencies (4)Versions (5)Used By (7)

MonkeysLegion Cache
===================

[](#monkeyslegion-cache)

A comprehensive caching package for the MonkeysLegion Framework with support for multiple drivers and PSR-16 SimpleCache compliance.

Features
--------

[](#features)

- **Multiple Cache Drivers**: File, Redis, Memcached, Array (in-memory)
- **PSR-16 Compliant**: Implements the Simple Cache interface
- **Cache Tagging**: Group cache entries and flush them together
- **Atomic Operations**: Increment/decrement numeric values
- **Remember Pattern**: Get or compute and cache values
- **CLI Commands**: Manage cache via command line
- **Helper Functions**: Convenient global functions for cache operations

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

[](#installation)

```
composer require monkeyscloud/monkeyslegion-cache
```

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

[](#configuration)

Create a `cache.php` configuration file:

```
return [
    'default' => 'file',

    'stores' => [
        'file' => [
            'driver' => 'file',
            'path' => __DIR__ . '/../storage/cache',
            'prefix' => 'ml_cache',
        ],

        'redis' => [
            'driver' => 'redis',
            'host' => '127.0.0.1',
            'password' => null,
            'port' => 6379,
            'database' => 1,
            'prefix' => 'ml_cache',
        ],

        'memcached' => [
            'driver' => 'memcached',
            'prefix' => 'ml_cache',
            'servers' => [
                ['host' => '127.0.0.1', 'port' => 11211, 'weight' => 100],
            ],
        ],

        'array' => [
            'driver' => 'array',
            'prefix' => 'ml_cache',
        ],
    ],
];
```

### MLC Configuration Format (Optional)

[](#mlc-configuration-format-optional)

The package also supports [MonkeysLegion-Mlc](https://github.com/MonkeysCloud/MonkeysLegion-Mlc) `.mlc` format:

```
# config/cache.mlc
cache.default = env("CACHE_DRIVER", "file")
cache.prefix = env("CACHE_PREFIX", "ml_cache")

cache.stores.redis.driver = "redis"
cache.stores.redis.host = env("REDIS_HOST", "127.0.0.1")
cache.stores.redis.port = env("REDIS_PORT", 6379)

```

**Benefits:**

- ✅ Clean dot-notation syntax
- ✅ Environment variable support with defaults
- ✅ Layered .env files
- ✅ Type-aware values

See [MLC-CONFIG.md](MLC-CONFIG.md) for complete documentation.

Basic Usage
-----------

[](#basic-usage)

### Initializing the Cache Manager

[](#initializing-the-cache-manager)

```
use MonkeysLegion\Cache\CacheManager;
use MonkeysLegion\Cache\Cache;

$config = require 'cache.php';
$manager = new CacheManager($config);

// Set the facade instance
Cache::setInstance($manager);
```

### Storing Items

[](#storing-items)

```
// Store for a specific time (in seconds)
Cache::set('key', 'value', 3600);

// Store forever
Cache::forever('key', 'value');

// Store if key doesn't exist
Cache::add('key', 'value', 3600);

// Store multiple items
Cache::putMany([
    'key1' => 'value1',
    'key2' => 'value2',
], 3600);
```

### Retrieving Items

[](#retrieving-items)

```
// Get an item
$value = Cache::get('key');

// Get with default value
$value = Cache::get('key', 'default');

// Get multiple items
$values = Cache::getMultiple(['key1', 'key2'], 'default');

// Get and delete
$value = Cache::pull('key');
```

### Remember Pattern

[](#remember-pattern)

```
// Get from cache or execute callback and store result
$users = Cache::remember('users', 3600, function() {
    return User::all();
});

// Remember forever
$settings = Cache::rememberForever('settings', function() {
    return Settings::all();
});
```

### Checking Existence

[](#checking-existence)

```
if (Cache::has('key')) {
    // Key exists
}
```

### Deleting Items

[](#deleting-items)

```
// Delete single item
Cache::delete('key');

// Delete multiple items
Cache::deleteMultiple(['key1', 'key2']);

// Clear all cache
Cache::clear();
```

### Incrementing/Decrementing

[](#incrementingdecrementing)

```
// Increment
Cache::increment('counter');
Cache::increment('counter', 5);

// Decrement
Cache::decrement('counter');
Cache::decrement('counter', 5);
```

### Cache Tagging

[](#cache-tagging)

```
// Store with tags
Cache::tags(['users', 'premium'])->set('user:1', $user, 3600);

// Retrieve tagged items
$user = Cache::tags(['users', 'premium'])->get('user:1');

// Flush all items with specific tags
Cache::tags(['users'])->clear();
Cache::tags(['users', 'premium'])->clear();
```

Using Different Stores
----------------------

[](#using-different-stores)

```
// Use specific store
Cache::store('redis')->set('key', 'value');

// Chain methods
Cache::store('redis')->tags(['api'])->set('key', 'value', 3600);
```

Helper Functions
----------------

[](#helper-functions)

```
// Get/Set cache
cache('key'); // Get
cache('key', 'value'); // Set
cache(['key1' => 'value1', 'key2' => 'value2']); // Set multiple

// Remember pattern
cache_remember('key', 3600, fn() => expensiveOperation());
cache_forever('key', fn() => expensiveOperation());

// Other operations
cache_forget('key');
cache_flush();
cache_has('key');
cache_pull('key');
cache_add('key', 'value', 3600);
```

CLI Commands
------------

[](#cli-commands)

### Clear Cache

[](#clear-cache)

```
# Clear default store
php ml cache:clear

# Clear specific store
php ml cache:clear --store=redis

# Clear by tags
php ml cache:clear --tags=users,posts
```

### Get Value

[](#get-value)

```
# Get value
php ml cache:get user:123

# Get from specific store
php ml cache:get user:123 --store=redis

# Get as JSON
php ml cache:get user:123 --format=json
```

### Set Value

[](#set-value)

```
# Set value
php ml cache:set user:123 "John Doe"

# Set with TTL (seconds)
php ml cache:set config:debug true --ttl=3600

# Set in specific store
php ml cache:set user:data '{"name":"John"}' --store=redis
```

### Forget Key

[](#forget-key)

```
# Delete key
php ml cache:forget user:123

# Delete multiple keys
php ml cache:forget user:123,user:456

# Delete from specific store
php ml cache:forget user:123 --store=redis
```

### Cache Statistics

[](#cache-statistics)

```
# Show stats for default store
php ml cache:stats

# Show stats for specific store
php ml cache:stats --store=redis
```

Cache Drivers
-------------

[](#cache-drivers)

### File Driver

[](#file-driver)

Stores cache in the filesystem with automatic directory structure and expiration handling.

```
'file' => [
    'driver' => 'file',
    'path' => '/path/to/cache',
    'prefix' => 'ml_cache',
],
```

### Redis Driver

[](#redis-driver)

Uses Redis for high-performance caching.

```
'redis' => [
    'driver' => 'redis',
    'host' => '127.0.0.1',
    'port' => 6379,
    'password' => null,
    'database' => 1,
    'prefix' => 'ml_cache',
],
```

### Memcached Driver

[](#memcached-driver)

Uses Memcached for distributed caching.

```
'memcached' => [
    'driver' => 'memcached',
    'persistent_id' => 'my_app',
    'servers' => [
        ['host' => '127.0.0.1', 'port' => 11211, 'weight' => 100],
    ],
    'prefix' => 'ml_cache',
],
```

### Array Driver

[](#array-driver)

In-memory cache for testing or single-request scenarios.

```
'array' => [
    'driver' => 'array',
    'prefix' => 'ml_cache',
],
```

Advanced Usage
--------------

[](#advanced-usage)

### Direct Store Access

[](#direct-store-access)

```
use MonkeysLegion\Cache\Stores\RedisStore;

$redis = new \Redis();
$redis->connect('127.0.0.1', 6379);

$store = new RedisStore($redis, 'prefix_');
$store->set('key', 'value', 3600);
```

### Custom Cache Key Prefix

[](#custom-cache-key-prefix)

```
Cache::store('redis')->getPrefix(); // Get prefix
```

### Working with Raw Connections

[](#working-with-raw-connections)

```
// Redis
$redis = Cache::store('redis')->getRedis();

// Memcached
$memcached = Cache::store('memcached')->getMemcached();
```

Testing
-------

[](#testing)

The ArrayStore is perfect for testing:

```
$cache = new CacheManager([
    'default' => 'array',
    'stores' => [
        'array' => ['driver' => 'array']
    ]
]);

// Cache won't persist between requests
```

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

[](#best-practices)

1. **Use appropriate TTL**: Set expiration times based on data volatility
2. **Use tags**: Group related cache items for easier management
3. **Remember pattern**: Simplifies cache-or-compute logic
4. **Prefix keys**: Prevent collisions in shared cache systems
5. **Clear strategically**: Use tags to clear related items without flushing all

License
-------

[](#license)

MIT License

###  Health Score

47

—

FairBetter than 94% of packages

Maintenance85

Actively maintained with recent releases

Popularity22

Limited adoption so far

Community16

Small or concentrated contributor base

Maturity55

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 80% 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 ~30 days

Total

4

Last Release

75d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/51e4df19377776baa8eafb605d9e7d2374b855c686f552c20d6856e94e3597c3?d=identicon)[yorchperaza](/maintainers/yorchperaza)

---

Top Contributors

[![yorchperaza](https://avatars.githubusercontent.com/u/2913369?v=4)](https://github.com/yorchperaza "yorchperaza (4 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

[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/redis-adapter

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

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

Neos Cache Framework

102.0M31](/packages/neos-cache)[graham-campbell/bounded-cache

A Bounded TTL PSR-16 Cache Implementation

101.9M6](/packages/graham-campbell-bounded-cache)[cache/void-adapter

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

183.0M44](/packages/cache-void-adapter)[infocyph/intermix

A Collection of useful PHP class functions.

136.4k1](/packages/infocyph-intermix)

PHPackages © 2026

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