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

ActiveLibrary[Caching](/categories/caching)

koded/cache-simple
==================

A PSR-16 caching library with support for several caching technologies. Supports JSON data caching in Redis.

3.1.1(1y ago)47.6k14BSD-3-ClausePHPPHP ^8.1CI failing

Since Apr 10Pushed 1y ago2 watchersCompare

[ Source](https://github.com/kodedphp/cache-simple)[ Packagist](https://packagist.org/packages/koded/cache-simple)[ RSS](/packages/koded-cache-simple/feed)WikiDiscussions master Synced 3w ago

READMEChangelog (10)Dependencies (9)Versions (27)Used By (4)

Koded - Simple Caching Library
==============================

[](#koded---simple-caching-library)

[![Latest Stable Version](https://camo.githubusercontent.com/22e4282f8e20cafb6e74343a5a904bc86448566aff8a5a5a0dbeecd86de14015/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6b6f6465642f63616368652d73696d706c652e737667)](https://packagist.org/packages/koded/cache-simple)[![Build Status](https://camo.githubusercontent.com/6532bbbc51f84ace6f78edab8f9f0bfc50b0acadaf06bb830a0fc8325732310d/68747470733a2f2f7472617669732d63692e6f72672f6b6f6465647068702f63616368652d73696d706c652e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/kodedphp/cache-simple)[![Code Coverage](https://camo.githubusercontent.com/24e57bbadacb44a064e1ff6c1c64d712f380c970c95bb5f6d2e161bc2c37a972/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6b6f6465647068702f63616368652d73696d706c652f6261646765732f636f7665726167652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/kodedphp/cache-simple/?branch=master)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/12036029cd02ca40f84fb2c86e786ca65e67459bc4b2ebe76f107b922cf04bd8/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6b6f6465647068702f63616368652d73696d706c652f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/kodedphp/cache-simple/?branch=master)[![Packagist Downloads](https://camo.githubusercontent.com/5141cb4baa9bbd91a2b3bd7651cad5d5f1bd659694976f7d0c34a2a293abae2a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6b6f6465642f63616368652d73696d706c652e737667)](https://packagist.org/packages/koded/cache-simple)[![Minimum PHP Version](https://camo.githubusercontent.com/183804d09fec16ca7b6209b007250b7d8db1b915042feb093a9f20e6e1f25359/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253345253344253230382e312d3838393242462e737667)](https://php.net/)

A [PSR-16](https://www.php-fig.org/psr/psr-16/) caching library for PHP 8 using several caching technologies. It supports JSON caching for Redis.

Requirements
------------

[](#requirements)

> The library is not tested on any Windows OS and may not work as expected there.

The recommended installation method is via [Composer](https://getcomposer.org)

```
composer require koded/cache-simple
```

### Redis

[](#redis)

There are two client flavors for Redis by using the

- [Redis extension](https://redis.io)
- [Predis library](https://github.com/nrk/predis)

and they are not mutually exclusive.

These clients supports JSON serialization for the cache, useful for handling the cached data in other programming languages.

Since there is no Redis native support for JSON serialization, it's done in userland and that always introduces some overhead. **Be aware that the native PHP and Igbinary functions are superior.**

- the `RedisClient` is preferred if Redis extension is installed
- the `PredisClient` can be used otherwise

```
// with Redis extension
simple_cache_factory('redis');

// with Predis library
simple_cache_factory('predis');
```

### Memcached

[](#memcached)

Please install the [Memcached extension](https://memcached.org).

Usage
-----

[](#usage)

The factory function always creates a new instance of specific `SimpleCacheInterface` client implementation.

```
/*
 * Creates a simple cache instance
 * with MemcachedClient and default configuration
 */

$cache = simple_cache_factory('memcached');
```

```
/*
 * Some configuration directives for the cache client
 * are passed in the second argument as array
 */

$cache = simple_cache_factory('redis', [
    'host'       => '127.0.0.1',
    'serializer' => 'json',
    'prefix'     => 'test:',
    'ttl'        => 3600 // 1 hour global TTL
]);
```

A bit verbose construction for the same instance is

```
$config = new ConfigFactory(['serializer' => 'json', 'prefix' => 'test:', 'ttl' => 3000]);
$cache = (new ClientFactory($config))->new('redis');
```

Configuration directives
------------------------

[](#configuration-directives)

Current available configuration classes

- [RedisConfiguration](#redisconfiguration)
- [MemcachedConfiguration](#memcachedconfiguration)
- [FileConfiguration](#fileconfiguration)
- [PredisConfiguration](#predisconfiguration)

### RedisConfiguration

[](#redisconfiguration)

Please refer to [Redis extension connect](https://github.com/phpredis/phpredis#connect-open) method.

ParameterValuehost127.0.0.1port6379timeout0.0reservednullretry0```
// Without defining the parameters the above directives are used as default
$cache = simple_cache_factory('redis');
```

#### Serializers

[](#serializers)

- `php` (default)
- `json`

> The special config directive is `binary(string)` for setting the internal serializer functions to either PHP native `un/serialize()`, `igbinary_un/serialize()` or `msgpack_un/pack()`.

```
$cache = simple_cache_factory('redis', [
    'binary' => \Koded\Stdlib\Serializer::MSGPACK
]);
```

The `binary` directive is effective if `igbinary` and/or `msgpack` extensions are installed and loaded. Otherwise it defaults to PHP `un/serialize()` functions.

> You can change the binary flag on already cached data, but you should invalidate the previously cached items, since they are already serialized and stored in the cache.

##### JSON serializer options

[](#json-serializer-options)

The **default** options for [json\_encode()](http://php.net/json_encode) function are:

- JSON\_PRESERVE\_ZERO\_FRACTION
- JSON\_UNESCAPED\_SLASHES
- JSON\_THROW\_ON\_ERROR

To set the desired options, use the `options` configuration directive:

```
$cache = simple_cache_factory('redis', [
    'serializer' => 'json',
    'options' => JSON_UNESCAPED_SLASHES | JSON_FORCE_OBJECT
]);
```

JSON options are applied with bitmask operators. The above example will

- remove `JSON_UNESCAPED_SLASHES` (because it's already set)
- add `JSON_FORCE_OBJECT`

### MemcachedConfiguration

[](#memcachedconfiguration)

Memcached argumentsTypeRequiredDescriptionidstringnoMemcached persistent\_id valueserversarraynoA list of nested array with \[server, port\] valuesoptionsarraynoA list of Memcached optionsttlintnoGlobal TTL (in seconds)The following options are set **by default** when an instance of `MemcachedConfiguration` is created, except for `OPT_PREFIX_KEY` which is there as a reminder that it may be set.

Memcached optionDefault valueOPT\_DISTRIBUTIONDISTRIBUTION\_CONSISTENTOPT\_SERVER\_FAILURE\_LIMIT2OPT\_REMOVE\_FAILED\_SERVERStrueOPT\_RETRY\_TIMEOUT1OPT\_LIBKETAMA\_COMPATIBLEtrueOPT\_PREFIX\_KEYnull> Options with `NULL` value will be removed.

There are many [Memcached options](http://php.net/manual/en/memcached.constants.php) that may suit the specific needs for the caching scenarios and this is something the developer/s needs to figure it out.

Examples:

```
[
    // Memcached client `persistent_id`
    'id' => 'items',

    // your Memcached servers list
    'servers' => [
        ['127.0.0.1', 11211],
        ['127.0.0.2', 11211],
        ['127.0.0.2', 11212],
    ],

    // Memcached client options
    'options' => [
        \Memcached::OPT_PREFIX_KEY            => 'i:',  // cache item prefix
        \Memcached::OPT_REMOVE_FAILED_SERVERS => false, // changes the default value
        \Memcached::OPT_DISTRIBUTION          => null   // remove this directive with NULL
    ],

    // the global expiration time (for ALL cached items)
    'ttl' => 120,
]
```

### PredisConfiguration

[](#predisconfiguration)

By default the parameters are:

ParameterValueschemetcphost127.0.0.1port6379Examples:

```
$cache = simple_cache_factory('predis');
```

```
$cache = simple_cache_factory('predis', [
    'scheme' => 'unix',
    'path' => '/path/to/redis.sock',
    'options' => [
        'prefix' => 'i:',
        'exceptions' => true,
        'parameters' => [
            'password' => getenv('REDIS_PASSWORD'),
            'database' => 1
        ]
    ]
]);
```

There are many configuration options for this package. Please refer to [Predis configuration page](https://github.com/nrk/predis#client-configuration).

### Shared Memory (shmop)

[](#shared-memory-shmop)

Requires a [PHP shmop extension](https://www.php.net/manual/en/book.shmop.php).

```
$cache = simple_cache_factory('shmop', [
    'dir' => '/path/to/app/cache', // optional
    'ttl' => null,                 // global TTL
]);
```

### FileConfiguration

[](#fileconfiguration)

Please avoid it on production environments, or use it as a last option.

If cache directory is not provided in the configuration, the PHP function [sys\_get\_temp\_dir()](http://php.net/sys_get_temp_dir) is used to store the cached files in the OS "temporary" directory.

```
$cache = simple_cache_factory('file', ['dir' => '/tmp']);
```

### MemoryClient

[](#memoryclient)

This client will store the cached items in the memory for the duration of the script's lifetime. It is useful for development, but not for production.

> `MemoryClient` is also the default client if you do not require a specific client in `cache_simple_factory()`

```
$cache = simple_cache_factory('memory');
$cache = simple_cache_factory();  // also creates a MemoryClient
```

Code quality
------------

[](#code-quality)

```
vendor/bin/phpunit
```

```
vendor/bin/phpbench run --report=default --group=factory
vendor/bin/phpbench run --report=default --group=read-write
```

or

```
vendor/bin/phpbench run --report=benchmark --group=read-write
```

### Benchmarks

[](#benchmarks)

The benchmarks are flaky and dependant on the environment. This table gives a non-accurate insight how client performs at write-read-delete operations, and should have an informative comparison.

To find out what may be the fastest choice for your environment, run

```
vendor/bin/phpbench run --report=default --group=read-write

+-----------------+-----------+-----------+-----------+--------+
| subject         | best      | mean      | worst     | rstdev |
+-----------------+-----------+-----------+-----------+--------+
| bench_predis    | 1.354ms   | 1.403ms   | 1.431ms   | ±2.49% |
| bench_redis     | 581.000μs | 592.667μs | 609.000μs | ±2.01% |
| bench_memcached | 581.000μs | 593.333μs | 606.000μs | ±1.72% |
| bench_file      | 355.000μs | 367.667μs | 385.000μs | ±3.45% |
| bench_shmop     | 349.000μs | 364.000μs | 374.000μs | ±2.97% |
| bench_memory    | 77.000μs  | 79.667μs  | 82.000μs  | ±2.58% |
+-----------------+-----------+-----------+-----------+--------+

```

License
-------

[](#license)

[![Software license](https://camo.githubusercontent.com/b3775a2de17853a90995faa104f941eef3ad3c40cc89e34b8b1eaea014614d4e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d425344253230332d2d436c617573652d626c75652e737667)](LICENSE)

The code is distributed under the terms of [The 3-Clause BSD license](LICENSE).

###  Health Score

46

—

FairBetter than 92% of packages

Maintenance50

Moderate activity, may be stable

Popularity23

Limited adoption so far

Community14

Small or concentrated contributor base

Maturity82

Battle-tested with a long release history

 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.

###  Release Activity

Cadence

Every ~120 days

Recently: every ~478 days

Total

26

Last Release

365d ago

Major Versions

1.9.1 → 2.0.02019-05-21

2.3.2 → 3.0.02021-05-03

PHP version history (8 changes)1.0.0PHP ^7.1

1.3.0PHP ~7.1

1.8.0PHP ^7.1.4

2.0.0PHP ^7.3

2.1.0PHP ^7.2

2.3.2PHP ~7.2

3.0.0PHP ^8

3.1.0PHP ^8.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/02c41fefd80a09d9f349706dbee9f45b9cfe539509881a05af4fa8d3517a878d?d=identicon)[kodeart](/maintainers/kodeart)

---

Top Contributors

[![kodeart](https://avatars.githubusercontent.com/u/202293?v=4)](https://github.com/kodeart "kodeart (224 commits)")

---

Tags

cachecachingfile-cachejsonjson-datajson-serializationmemcachedpsr-16redisshmopjsonrediscachecachingpsr-16memcachedfile cacheshmop

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[tedivm/stash-bundle

Incorporates the Stash caching library into Symfony.

841.4M16](/packages/tedivm-stash-bundle)[aplus/cache

Aplus Framework Cache Library

171.6M4](/packages/aplus-cache)[mmamedov/page-cache

PageCache is a lightweight PHP library for full page cache. It uses various strategies to differentiate among separate versions of the same page.

7813.1k1](/packages/mmamedov-page-cache)[webarchitect609/bitrix-cache

Comfortable fluent interface for Bitrix cache. Anti-stampede cache protection.

2731.5k8](/packages/webarchitect609-bitrix-cache)

PHPackages © 2026

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