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

ActiveLibrary[Caching](/categories/caching)

cleup/cache
===========

Flexible caching library for PHP with multiple drivers support

1.0.3(7mo ago)0131MITPHPPHP ^8.1

Since Oct 4Pushed 7mo agoCompare

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

READMEChangelog (4)Dependencies (2)Versions (5)Used By (1)

Cleup Cache Library
===================

[](#cleup-cache-library)

A powerful, flexible caching library for PHP with support for multiple storage drivers including file-based, Redis, and Memcached.

Features
--------

[](#features)

- Multiple Drivers: File, Redis, and Memcached support
- Simple API: Intuitive and consistent interface across all drivers
- Namespace Support: Organize cache entries with namespaces
- Memory Caching: Local driver includes in-memory caching for performance
- Garbage Collection: Automatic cleanup of expired entries
- Statistics: Get detailed cache statistics
- Flexible Configuration: Easy setup and configuration

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

[](#installation)

```
composer require cleup/cache
```

Basic Setup
-----------

[](#basic-setup)

### Quick Start

[](#quick-start)

```
use Cleup\Cache\CacheManager;

// Configure cache drivers
CacheManager::configure([
    'default' => 'local', // or 'type:namespace'
    'local' => [
        'storage_path' => '/path/to/cache',
        'default_ttl' => 3600
    ],
    'redis' => [
        'host' => '127.0.0.1',
        'port' => 6379,
        'prefix' => 'app:'
    ]
    'local:myapp' => [
        // ...
    ],
    'redis:new_server': [
        // ...
    ],
    'memcached:sessions' => [
        // ...
    ]
]);

// Use the default driver
CacheManager::set('key', 'value', 3600);
$value = CacheManager::get('key');

// Use a driver with a specific type and namespace.
CacheManager::driver('redis:new_server')->set('key', 'value');
CacheManager::driver('memcached:sessions')->get('key');
```

### Manual Driver Setup

[](#manual-driver-setup)

```
use Cleup\Cache\Drivers\LocalDriver;
use Cleup\Cache\Cache;

// Local file driver
$localDriver = new LocalDriver([
    'storage_path' => '/tmp/cache',
    'default_ttl' => 3600
]);
// Or
$localDriver = (new LocalDriver())
  ->storagePath('/tmp/cache')
  ->defaultTtl(3600);

$cache = new Cache($localDriver);
$user = ['id' => 1, 'name' => 'Eduard'];
$cache->set('user', $user, 1800);
$cahe->get('user');
```

Method Reference
----------------

[](#method-reference)

### Basic Operations

[](#basic-operations)

Retrieve an item from cache. `get(string $key): mixed`

```
$value = $cache->get('user_profile');
if ($value === null) {
    // Cache missing
}
```

Store an item in cache. `set(string $key, mixed $value, ?int $ttl = null): bool`

```
$success = $cache->set('user', $userData, 3600); // 1 hour
```

Remove an item from cache. `delete(string $key): bool`

```
$cache->delete('user');
```

Check if an item exists in cache. `has(string $key): bool`

```
if ($cache->has('user:1')) {
    // Item exists
}
```

Clear all cache items. `clear(): bool`

```
$cache->clear();
```

### Advanced Operations

[](#advanced-operations)

Get an item or store the default value if it doesn't exist. `remember(string $key, callable $callback, ?int $ttl = null): mixed`

```
$user = $cache->remember('user:1', function() {
    return User::find(1);
}, 3600);
```

Get and remove an item from cache. `pull(string $key): mixed`

```
$value = $cache->pull('temporary_data');
```

Store an item only if it doesn't already exist. `add(string $key, mixed $value, ?int $ttl = null): bool`

```
$added = $cache->add('unique_key', $value); // Returns false if key exists
```

Store an item permanently (no expiration). `forever(string $key, mixed $value): bool`

```
$cache->forever('config_data', $config);
```

### Batch Operations

[](#batch-operations)

Get multiple items. `getMultiple(array $keys): array`

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

Store multiple items. `setMultiple(array $values, ?int $ttl = null): bool`

```
$success = $cache->setMultiple([
    'user:1' => $user1,
    'user:2' => $user2
], 3600);
```

Delete multiple items. `deleteMultiple(array $keys): bool`

```
$cache->deleteMultiple(['user:1', 'user:2']);
```

### Numeric Operations

[](#numeric-operations)

Increment a numeric value. `increment(string $key, int $value = 1): int|false`

```
$newValue = $cache->increment('page_views', 1);
```

Decrement a numeric value. `decrement(string $key, int $value = 1): int|false`

```
$newValue = $cache->decrement('remaining_credits', 1);
```

### Utility Methods

[](#utility-methods)

Get cache statistics (unique for each driver). `getStats(): array`

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

Check if the driver is connected. `isConnected(): bool`

```
if ($cache->isConnected()) {
    // Driver is ready
}
```

Drivers
-------

[](#drivers)

### Local Driver (File-based)

[](#local-driver-file-based)

The local driver stores cache items as files on the filesystem with in-memory caching for performance.

##### Configuration

[](#configuration)

```
$driver = new LocalDriver([
    'storage_path' => '/path/to/cache',    // Cache directory
    'file_extension' => '.cache',          // File extension
    'serializer' => 'php',                 // Serialization method
    'gc_probability' => 1,                 // Garbage collection probability
    'gc_divisor' => 100,                   // Garbage collection divisor
    'default_ttl' => 3600                  // Default TTL in seconds
]);
```

##### Fluent Configuration

[](#fluent-configuration)

```
$driver = (new LocalDriver())
    ->storagePath('/custom/cache/path')
    ->fileExtension('.data')
    ->serializer('php')
    ->garbageCollection(5, 100) // 5% probability
    ->defaultTtl(7200);
```

##### Features

[](#features-1)

- In-memory caching: Recent items stored in memory for fast access
- File-based storage: Persistent storage on filesystem
- Automatic garbage collection: Removes expired items
- Atomic operations: Safe concurrent access

### Redis Driver

[](#redis-driver)

Redis driver for high-performance caching with Redis server.

##### Configuration

[](#configuration-1)

```
$driver = new RedisDriver([
    'host' => '127.0.0.1',         // Redis server host
    'port' => 6379,                // Redis server port
    'timeout' => 2.5,              // Connection timeout
    'persistent' => false,         // Persistent connection
    'password' => 'secret',        // Authentication password
    'database' => 0,               // Redis database number
    'prefix' => 'app:cache:',      // Key prefix
    'default_ttl' => 3600          // Default TTL in seconds
]);
```

##### Fluent Configuration

[](#fluent-configuration-1)

```
$driver = (new RedisDriver())
    ->host('redis.example.com')
    ->port(6380)
    ->password('secret')
    ->database(1)
    ->prefix('myapp:')
    ->persistent(true)
    ->defaultTtl(7200)
    ->connect(); // Must call connect() manually with fluent configuration
```

##### Features

[](#features-2)

- Persistent connections: Optional persistent connections for performance
- Key prefixing: Automatic key namespacing
- Pipeline operations: Efficient batch operations
- Serialization: Automatic serialization of complex data

### Memcached Driver

[](#memcached-driver)

Memcached driver for distributed caching.

##### Configuration

[](#configuration-2)

```
$driver = new MemcachedDriver([
    'host' => '127.0.0.1',         // Memcached server host
    'port' => 11211,               // Memcached server port
    'options' => [],               // Memcached options
    'prefix' => 'app:',            // Key prefix
    'default_ttl' => 3600          // Default TTL in seconds
]);
```

##### Fluent Configuration

[](#fluent-configuration-2)

```
$driver = (new MemcachedDriver())
    ->host('memcached.example.com')
    ->port(11211)
    ->prefix('app:')
    ->setOption(\Memcached::OPT_COMPRESSION, true)
    ->setOption(\Memcached::OPT_DISTRIBUTION, \Memcached::DISTRIBUTION_CONSISTENT)
    ->defaultTtl(7200)
    ->connect(); // Must call connect() manually with fluent configuration
```

##### Features

[](#features-3)

- Multiple servers: Support for multiple Memcached servers
- Compression: Optional data compression
- Consistent hashing: Better key distribution
- Binary protocol: Optional binary protocol support

Cache Manager
-------------

[](#cache-manager)

The Cache Manager provides a static interface for managing multiple cache drivers and namespaces.

### Configuration

[](#configuration-3)

```
use Cleup\Cache\CacheManager;

CacheManager::configure([
    'default' => 'local',
    'local' => [
        'storage_path' => '/tmp/local_cache',
        'default_ttl' => 300
    ],
    'local:forever' => [
        'storage_path' => '/tmp/local_cache',
        'default_ttl' => 0
    ]
    'redis' => [
        'host' => '127.0.0.1',
        'port' => 6379,
        'prefix' => 'redisapp:',
        'default_ttl' => 3600
    ],

    'redis:sessions' => [
        'host' => '127.0.0.1',
        'port' => 6379,
        'database' => 1,
        'prefix' => 'sessions:',
        'default_ttl' => 1800
    ],
    'memcached' => [
        'host' => '127.0.0.1',
        'port' => 11211,
        'options' => [],
        'prefix' => 'memcached_app_',
        'default_ttl' => 3600
    ]
]);

//Or by creating a new instance of the class
$cacheManager = new CacheManager();
$cacheManager->configure([
    //...
]);
```

### Usage

[](#usage)

Direct Driver Access

```
// Access specific driver
$foreverLocalData = CacheManager::driver('local:forever');
$sessionCache = CacheManager::driver('redis:sessions');

$foreverLocalData->set('data', $value);
$sessionCache->set('user_session', $sessionData);
```

Static Method Calls

```
// Use default driver
CacheManager::set('key', 'value');
$value = CacheManager::get('key');
```

Cache Helper Function
---------------------

[](#cache-helper-function)

The library includes a convenient global helper function cache() that provides a simplified interface for common cache operations. `cache(?string $key = null, mixed $value = null): mixed`

```
// Get value by key
$user = cache('user');
// Equivalent to:
$user = CacheManager::get('user');

// Set value with key
cache('user', $userData, 3600);
// Equivalent to:
CacheManager::set('user', $userData, 3600);

# Set Value with TTL

// Set value with specific TTL (using method chaining)
cache()->set('user:123', $userData, 3600);
// Or using the manager directly
cache('user:123', $userData, 3600); // Note: This syntax requires the helper to be extended

// Get CacheManager instance for advanced operations
$cache = cache();
$cache->driver('redis')->remember('key', fn() => compute(), 1800);
```

###  Health Score

33

—

LowBetter than 75% of packages

Maintenance63

Regular maintenance activity

Popularity5

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity47

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 66.7% 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 ~1 days

Total

4

Last Release

223d ago

### Community

Maintainers

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

---

Top Contributors

[![cleup](https://avatars.githubusercontent.com/u/156127069?v=4)](https://github.com/cleup "cleup (6 commits)")[![priveted](https://avatars.githubusercontent.com/u/18353516?v=4)](https://github.com/priveted "priveted (3 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[react/cache

Async, Promise-based cache interface for ReactPHP

444112.4M40](/packages/react-cache)[wp-media/wp-rocket

Performance optimization plugin for WordPress

7431.3M3](/packages/wp-media-wp-rocket)[illuminate/cache

The Illuminate Cache package.

12835.6M1.4k](/packages/illuminate-cache)[colinmollenhour/php-redis-session-abstract

A Redis-based session handler with optimistic locking

6325.6M14](/packages/colinmollenhour-php-redis-session-abstract)[cheprasov/php-redis-client

Php client for Redis. It is a fast, fully-functional and user-friendly client for Redis, optimized for performance. RedisClient supports the latest versions of Redis starting from 2.6 to 6.0

1281.2M21](/packages/cheprasov-php-redis-client)[amphp/redis

Efficient asynchronous communication with Redis servers, enabling scalable and responsive data storage and retrieval.

165634.7k44](/packages/amphp-redis)

PHPackages © 2026

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