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(10mo ago)0131MITPHPPHP ^8.1

Since Oct 4Pushed 10mo 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 1w 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

31

—

LowBetter than 65% of packages

Maintenance54

Moderate activity, may be stable

Popularity5

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity48

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

313d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/156127069?v=4)[cleup](/maintainers/cleup)[@cleup](https://github.com/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

[iazaran/smart-cache

Smart Cache is a caching optimization package designed to enhance the way your Laravel application handles data caching. It intelligently manages large data sets by compressing, chunking, or applying other optimization strategies to keep your application performant and efficient.

21114.2k](/packages/iazaran-smart-cache)[phpfastcache/phpssdb

PHP SSDB Driver for phpFastCache

14736.9k1](/packages/phpfastcache-phpssdb)[rapidwebltd/rw-file-cache

RW File Cache is a PHP File-based Caching Library. Its syntax is designed to closely resemble the PHP memcache extension.

15196.8k7](/packages/rapidwebltd-rw-file-cache)[yuzuru-s/redis-recommend

Wrapping Redis's sorted set APIs for specializing recommending operations.

392.9k](/packages/yuzuru-s-redis-recommend)[ichhabrecht/intcache

Turn uncachable page objects into cacheable links

193.9k](/packages/ichhabrecht-intcache)

PHPackages © 2026

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