PHPackages                             armin-dev/cache-box - 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. armin-dev/cache-box

ActiveLibrary[Caching](/categories/caching)

armin-dev/cache-box
===================

00PHP

Since Sep 30Pushed 7mo agoCompare

[ Source](https://github.com/PouyaniArmin/CacheBox)[ Packagist](https://packagist.org/packages/armin-dev/cache-box)[ RSS](/packages/armin-dev-cache-box/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

CacheBox
========

[](#cachebox)

CacheBox is a flexible PHP caching library that allows developers to store and retrieve data easily using multiple drivers, including file system, Memcached, and Redis. It provides a unified API for caching and simplifies cache management in PHP projects.

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

[](#installation)

### Requirements

[](#requirements)

- PHP 8.0 or higher
- PHP extensions:
    - `redis` (for RedisDriver)
    - `memcached` (for MemcacheDriver)
- File write permissions (for FileCache)

### Installation via Composer

[](#installation-via-composer)

You can install CacheBox using Composer:

```
composer require armin-dev/cache-box
```

```
require __DIR__ . '/vendor/autoload.php';

use ArminDev\CacheBox\CacheBox;
```

Drivers
-------

[](#drivers)

### Memcached

[](#memcached)

- Supports two formats: `string` and `json`.
- Data must be stored in one of these formats.
- TTL (expiration) is fully supported.
- Requires Memcached server to be running and accessible.

### Redis

[](#redis)

- No format selection required; Redis can store any type of data directly.
- TTL (expiration) is fully supported.
- Requires Redis server to be running and accessible.

Usage / Examples
----------------

[](#usage--examples)

### Using FileCache

[](#using-filecache)

```
use ArminDev\CacheBox\CacheBox;

$cache = new CacheBox();
$cache->driver('file')
      ->path(__DIR__ . '/cache')   // optional, default directory will be used
      ->directory('my_cache')      // optional
      ->format('json');            // set format: json, serialize, txt

$cache->set('post_1', ['title' => 'Hello World'], '1h');
$data = $cache->get('post_1');
print_r($data);
```

### Using Memcached

[](#using-memcached)

```
use ArminDev\CacheBox\CacheBox;

$cache = new CacheBox();
$cache->driver('memcached')
      ->server('127.0.0.1', 11211)
      ->setFormat('json');        // required for Memcached

$cache->set('post_2', ['title' => 'Memcached Example'], '30m');
$data = $cache->get('post_2');
print_r($data);
```

### Using Redis

[](#using-redis)

```
use ArminDev\CacheBox\CacheBox;

$cache = new CacheBox();
$cache->driver('redis')
      ->server('127.0.0.1', 6379); // no format needed

$cache->set('post_3', ['title' => 'Redis Example'], '2h');
$data = $cache->get('post_3');
print_r($data);
```

TTL / Expiration
----------------

[](#ttl--expiration)

CacheBox supports setting expiration times (TTL) for cached items. You can provide TTL as a string with a numeric value followed by a unit:

- `s` → seconds
- `m` → minutes
- `h` → hours
- `d` → days

**Examples:**

```
use ArminDec\CacheBox\CacheBox;

$cache = new CacheBox();
$cache->driver('file')
      ->path(__DIR__ . '/cache')
      ->directory('my_cache')
      ->format('json');

// TTL in seconds
$cache->set('post_sec', 'Data expires in 30 seconds', '30s');

// TTL in minutes
$cache->set('post_min', 'Data expires in 15 minutes', '15m');

// TTL in hours
$cache->set('post_hour', 'Data expires in 2 hours', '2h');

// TTL in days
$cache->set('post_day', 'Data expires in 5 days', '5d');
```

Configuration / Options
-----------------------

[](#configuration--options)

CacheBox provides some configurable options depending on the driver you use:

### FileCache

[](#filecache)

- `path($path)` → set the base path for cache files (required).
- `directory($dir)` → set a subdirectory inside the base path (optional).
- `format($type)` → choose the format: `json`, `serialize`, `txt` (required).

### Memcached

[](#memcached-1)

- `server($host, $port)` → set Memcached server host and port (required).
- `setFormat($type)` → choose format: `string` or `json` (required).

### Redis

[](#redis-1)

- `server($host, $port)` → set Redis server host and port (required).
- No format selection is needed; Redis stores data directly.

**Example:**

```
$cache = new CacheBox();
$cache->driver('file')
      ->path(__DIR__ . '/cache')
      ->directory('my_cache')
      ->format('json');

$cache->driver('memcached')
      ->server('127.0.0.1', 11211)
      ->setFormat('json');

$cache->driver('redis')
      ->server('127.0.0.1', 6379);
```

Error Handling / Exceptions
---------------------------

[](#error-handling--exceptions)

CacheBox throws exceptions in cases where operations fail or invalid configurations are provided. You should handle these exceptions using `try/catch` blocks to prevent application crashes.

### Common Exceptions

[](#common-exceptions)

CacheBox may throw exceptions in several scenarios. Examples:

```
$cache = new CacheBox();

try {
    // Driver Not Supported
    $cache->driver('unknown');
} catch (Exception $e) {
    echo "Driver Error: " . $e->getMessage() . PHP_EOL;
}

try {
    // Redis server not reachable
    $cache->driver('redis')->server('127.0.0.1', 6379);
} catch (Exception $e) {
    echo "Redis Error: " . $e->getMessage() . PHP_EOL;
}

try {
    // Memcached server not reachable
    $cache->driver('memcached')->server('127.0.0.1', 11211);
} catch (Exception $e) {
    echo "Memcached Error: " . $e->getMessage() . PHP_EOL;
}

try {
    // FileCache file missing or expired
    $data = $cache->driver('file')->get('nonexistent_key');
} catch (Exception $e) {
    echo "FileCache Error: " . $e->getMessage() . PHP_EOL;
}
```

Contributing
------------

[](#contributing)

Contributions to CacheBox are welcome! You can help by:

- Reporting bugs or issues
- Suggesting new features
- Submitting pull requests with improvements

Before submitting a pull request, please make sure your code follows the existing coding standards and passes any tests.

---

License
-------

[](#license)

CacheBox is released under the MIT License. See the [LICENSE](LICENSE) file for more details.

###  Health Score

16

—

LowBetter than 5% of packages

Maintenance44

Moderate activity, may be stable

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity13

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.

### Community

Maintainers

![](https://www.gravatar.com/avatar/9a466339f302157a8be2df7595714453af381012cc190f124f65feb3c31a28ee?d=identicon)[PouyaniArmin](/maintainers/PouyaniArmin)

---

Top Contributors

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

### Embed Badge

![Health badge](/badges/armin-dev-cache-box/health.svg)

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

###  Alternatives

[predis/predis

A flexible and feature-complete Redis/Valkey client for PHP.

7.8k305.7M2.4k](/packages/predis-predis)[snc/redis-bundle

A Redis bundle for Symfony

1.0k39.4M67](/packages/snc-redis-bundle)[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)

PHPackages © 2026

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