PHPackages                             romeoz/rock-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. [Database &amp; ORM](/categories/database)
4. /
5. romeoz/rock-cache

ActiveLibrary[Database &amp; ORM](/categories/database)

romeoz/rock-cache
=================

Unified API for key-value storages in memory. As a storage can be used: APC, Redis, Memcache, Couchbase or MongoDB. All storage objects have one interface, so you can switch them without changing the working code.

0.16.0(8y ago)73.1k16MITPHPPHP &gt;=5.4.0

Since Jun 28Pushed 8y ago3 watchersCompare

[ Source](https://github.com/romeOz/rock-cache)[ Packagist](https://packagist.org/packages/romeoz/rock-cache)[ RSS](/packages/romeoz-rock-cache/feed)WikiDiscussions master Synced today

READMEChangelog (10)Dependencies (3)Versions (19)Used By (6)

Cache library
=============

[](#cache-library)

[![Latest Stable Version](https://camo.githubusercontent.com/1d9ebdcec985e2d43958404ee0e0cdea91b7090d14b75b9db379be334c255fbd/68747470733a2f2f706f7365722e707567782e6f72672f726f6d654f7a2f726f636b2d63616368652f762f737461626c652e737667)](https://packagist.org/packages/romeOz/rock-cache)[![Total Downloads](https://camo.githubusercontent.com/991927fcada5228efd74d3fab914c9171dc361e770cb244f4f542e59b3e2f193/68747470733a2f2f706f7365722e707567782e6f72672f726f6d654f7a2f726f636b2d63616368652f646f776e6c6f6164732e737667)](https://packagist.org/packages/romeOz/rock-cache)[![Build Status](https://camo.githubusercontent.com/15dbea6e8a04ca012cce82f3f763e4f875922a222773b8e050aebed8f7f8f5a6/68747470733a2f2f7472617669732d63692e6f72672f726f6d654f7a2f726f636b2d63616368652e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/romeOz/rock-cache)[![Coverage Status](https://camo.githubusercontent.com/a843ff4ac00c2109897cbdfd0119fa7f57a27f1a29a5fd55f9afb6ef5f6ffb60/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f726f6d654f7a2f726f636b2d63616368652f62616467652e737667)](https://coveralls.io/r/romeOz/rock-cache)[![License](https://camo.githubusercontent.com/7f8cf7b27f21c4efe96b7a8bd6c8fd530a3796dae393b9caf6db8e14d7c7c4e6/68747470733a2f2f706f7365722e707567782e6f72672f726f6d654f7a2f726f636b2d63616368652f6c6963656e73652e737667)](https://packagist.org/packages/romeOz/rock-cache)

What storages can be used:

- [Memcached](http://memcached.org/)
- [APCu](http://pecl.php.net/package/APCu)
- [Redis](http://redis.io)
- [Couchbase](http://www.couchbase.com)
- [MongoDB](https://www.mongodb.org/)
- CacheStub (stub for caching)

All storage objects have one interface, so you can switch them without changing the working code.

Features
--------

[](#features)

- One interface for all storages - you can change storage without changing your code
- Tagging cache (approach versioning and grouping)
- Locking - "race condition" ("dog-pile" or "cache miss storm") effects are excluded
- Serializer for value (json or PHP-serializer)
- Automatic unserialization
- Standalone module/component for [Rock Framework](https://github.com/romeOz/rock)

Table of Contents
-----------------

[](#table-of-contents)

- [Installation](#installation)
- [Quick Start](#quick-start)
    - [Memcached](#memcached)
    - [MongoDB](#mongodb)
    - [Locking key](#locking-key)
- [Documentation](#documentation)
- [Demo](#demo)
- [Requirements](#requirements)
- [Storages comparison](#storages-comparison)
- [Differences between the approaches a tagging](#differences-between-the-approaches-a-tagging)
    - [Grouping tags](#grouping-tags)
    - [Versioning tags](#versioning-tags)

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

[](#installation)

From the Command Line:

```
composer require romeoz/rock-cache

```

or in your composer.json:

```
{
    "require": {
        "romeoz/rock-cache": "*"
    }
}
```

Quick Start
-----------

[](#quick-start)

\####Memcached

```
$config = [
    'hashKey' => CacheInterface::HASH_MD5, // Default: HASH_MD5
    'serializer' => CacheInterface::SERIALIZE_JSON // Default: SERIALIZE_PHP - php serializator
];
$memcached = new \rock\cache\Memcached($config); // or \rock\cache\versioning\Memcached for approach versioning

$tags = ['tag_1', 'tag_2'];
$value = ['foo', 'bar'];
$expire = 0; // If use expire "0", then time to live infinitely
$memcached->set('key_1', $value, $expire, $tags);

// automatic unserialization
$memcached->get('key_1'); // result: ['foo', 'bar'];

$memcached->flush(); // Invalidate all items in the cache
```

\####MongoDB

```
$connection = new \rock\mongodb\Connection;
$collection = $connection->getCollection('cache')
$collection->createIndex('id', ['unique' => true]);
$collection->createIndex('expire', ['expireAfterSeconds' => 0]); // create TTL index

$config = [
    'storage' => $connection,
    'cacheCollection' => 'cache'
];
$mongoCache = new \rock\cache\MongoCache($config);

...
```

\####Locking key

Race conditions can occur in multi-threaded mode. To avoid the effect, you need to install a lock on the key.

```
$memcached = new \rock\cache\Memcached

$value = $memcached->get('key_1');
if ($value !== false) {
    return $value;
}

if ($memcached->lock('key_1')) {

    // the query to DBMS or other...

    $memcached->set('key_1', 'foo');
    $memcached->unlock('key_1');
}
```

Documentation
-------------

[](#documentation)

\####get($key) Returns value by key.

\####getMulti(array $keys) Returns multiple values by keys.

\####set($key, mixed $value, $expire = 0, array $tags = null) Sets a value to cache.

\####setMulti($key, mixed $value, $expire = 0, array $tags = null) Sets a multiple key-values to cache.

\####add($key, mixed $value, $expire = 0, array $tags = null) Adds a value to cache.

> Return false, if already exists on the server.

\####exists($key) Checks existence key.

\####touch($key, $expire = 0) Changes expire (TTL) for key.

\####touchMulti(array $keys, $expire = 0) Changes expire (TTL) for multiple keys .

\####increment($key, $offset = 1, $expire = 0, $create = true) Increment a value to cache.

\####decrement($key, $offset = 1, $expire = 0, $create = true) Decrement a value to cache.

\####remove($key) Removes value from cache.

\####removeMulti(array $keys) Removes multiple values from cache.

\####getTag($tag) Returns a keys in accordance with tag.

\####getMultiTags(array $tags) Returns a keys in accordance with multiple tags.

\####existsTag($tag) Checks existence tag.

\####removeTag($tag) Removes a tag.

\####removeMultiTag(array $tags) Removes a multiple tags.

\####getAllKeys() Returns all keys.

> Supported: `Memcached`, `Redis`, `APC`.

\####getAll() Returns all values.

> Supported: `Memcached`, `APC`.

\####lock($key) Sets a lock on the key.

\####unlock($key) Unlocking key.

\####flush() Removes all values from cache.

\####status() Returns a status server.

> Supported: `Memcached`, `Memcache`, `Redis`, `APC`, `Couchbase`.

\####getStorage() Returns a native instance cache-storage.

[Demo](https://github.com/romeOz/docker-rock-cache)
---------------------------------------------------

[](#demo)

- [Install Docker](https://docs.docker.com/installation/) or [askubuntu](http://askubuntu.com/a/473720)
- `docker run --name demo -d -p 8080:80 romeoz/docker-rock-cache`
- Open demo

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

[](#requirements)

You can use each storage separately, requirements are individually for storages.

- **PHP 5.4+ and 7.0+**
- [Redis 2.8/3.0/3.2/4.0](http://redis.io). Should be installed `apt-get install redis-server` or `docker run --name redis -d -p 6379:6379 romeoz/docker-redis:4.0` (recommended). Also should be installed [PHP extension](http://pecl.php.net/package/redis) `apt-get install php-redis`
- [Memcached](http://memcached.org/). Should be installed `apt-get install memcached` or `docker run --name memcached -d -p 11211:11211 romeoz/docker-memcached` (recommended). Also should be installed php-extension [Memcache](http://pecl.php.net/package/memcache) `apt-get install php-memcache` or [Memcached](http://pecl.php.net/package/memcached) `apt-get install php-memcached`.

> php-extension Memcached [require dependencies](https://github.com/php-memcached-dev/php-memcached#dependencies)

- [APCu](http://pecl.php.net/package/APCu). Should be installed `apt-get install php-apcu`.

> For PHP 5.6 and lower allowed pecl-extensions APCu 4.0 and lower. [Example installation](https://github.com/romeOz/docker-phpfpm/blob/master/5.6/full/Dockerfile#L24-L27).

- Couchbase DB 4.x.x. PHP 5.6 or higher, php-extension couchbase 2.3.x-2.4.x. [Step-by-step installation](http://developer.couchbase.com/documentation/server/4.1/sdks/php-2.0/download-links.html) or `docker run --name couchbase -d couchbase/server:community-4.1.1` ([Example installation](https://github.com/romeOz/docker-phpfpm/blob/master/5.6/full/Dockerfile#L15-L23)).
- MongoDB 2.6-3.0. For using [MongoDB](https://www.mongodb.org/) as storage required [Rock MongoDB](https://github.com/romeOz/rock-mongodb): `composer require romeoz/rock-mongodb`

> All unbolded dependencies is optional

There is a ready docker-container: `docker run --name phpfpm_full -d romeoz/docker-phpfpm:5.6-full`. But, it may be redundant for you because of the many of installed pecl-extensions

Storages comparison
-------------------

[](#storages-comparison)

**Redis** is the best key-value storage for cache. Use **Couchbase** if you need fault-tolerant and very easy scalable cluster and if you can afford it ([recommended hardware requirements](http://docs.couchbase.com/couchbase-manual-2.2/#resource-requirements)). Also, data in Redis and Couchbase storages will be restored even after server reboot.

Differences between the approaches a tagging
--------------------------------------------

[](#differences-between-the-approaches-a-tagging)

\###Grouping tags

Fastest method, but there is a possibility of overflow cache.

Set a value:

```
$cache = new \rock\cache\Memcached;

$cache->set('key_1', 'text_1', 0, ['tag_1', 'tag_2']);
$cache->set('key_2', 'text_2', 0, ['tag_1']);
```

View in memory:

```
key_1: text_1
key_2: text_2

tag_1: [key_1, key_2]
tag_2: [key_1]

```

Removing tag:

```
$cache->removeTag('tag_2');
```

View in memory:

```
key_2: text_2

tag_1: [key_1, key_2]

```

\###Versioning tags

Is the best practice, but slower than the approach with the grouping tags, because when getting the cache containing tags, sent multiple requests to compare versions. There is no cache overflows.

**References**: [nablas by D.Koterov (RUS)](http://dklab.ru/chicken/nablas/47.html) or ["Reset group caches and tagging" by A.Smirnov (RUS)](http://smira.ru/posts/20081029web-caching-memcached-5.html).

Set a value:

```
$cache = new \rock\cache\versioning\Memcached;

$cache->set('key_1', 'text_1', 0, ['tag_1', 'tag_2']);
$cache->set('key_2', 'text_2', 0, ['tag_1']);
```

View in memory:

```
key_1: [
    value : text_1,
    tags : [
        tag_1 : 0.20782200 1403858079,
        tag_2 : 0.20782200 1403858079
    ]
]
// tag : microtime

key_2: [
    value : text_2,
    tags : [
        tag_1 : 0.20782200 1403858079,
    ]
]

tag_1: 0.20782200 1403858079
tag_2: 0.20782200 1403858079

```

Removing tag:

```
$cache->removeTag('tag_2');
```

View in memory:

```
key_1: [
    value : text_1,
    tags : [
        tag_1 : 0.20782200 1403858079,
        tag_2 : 0.20782200 1403858079
    ]
]
key_2: [
    value : text_2,
    tags : [
        tag_1 : 0.20782200 1403858079,
    ]
]

tag_1: 0.20782200 1403858079
tag_2: 0.29252400 1403858537

```

Returns value:

```
$cache->get('key_1');
// result: false
```

View in memory:

```
key_2: [
    value : text_2,
    tags : [
        tag_1 : 0.20782200 1403858079,
    ]
]

tag_1: 0.20782200 1403858079

```

License
-------

[](#license)

The Rock Cache library is open-sourced software licensed under the [MIT license](http://opensource.org/licenses/MIT)

###  Health Score

31

—

LowBetter than 66% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity22

Limited adoption so far

Community18

Small or concentrated contributor base

Maturity57

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 99.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 ~82 days

Recently: every ~232 days

Total

18

Last Release

2984d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/23c5d84a59845d751cb69f5469986579b9312c54c898b366fefdc05baaa80a9c?d=identicon)[romeOz](/maintainers/romeOz)

---

Top Contributors

[![romeOz](https://avatars.githubusercontent.com/u/3135712?v=4)](https://github.com/romeOz "romeOz (329 commits)")[![chistaesse](https://avatars.githubusercontent.com/u/22150961?v=4)](https://github.com/chistaesse "chistaesse (1 commits)")

---

Tags

apcucachecouchbasememcachedmongodbphpredisrediscachingmemoryrace conditionmemcachedmongodbapcmemcachecouchbasedog piletagging cache

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[phpfastcache/phpfastcache

PHP Abstract Cache Class - Reduce your database call using cache system. Phpfastcache handles a lot of drivers such as Apc(u), Cassandra, CouchBase, Couchdb, Dynamodb, Firestore, Mongodb, Files, (P)redis, Leveldb, Memcache(d), Ravendb, Ssdb, Sqlite, Wincache, Xcache, Zend Data Cache.

2.5k5.3M141](/packages/phpfastcache-phpfastcache)[apix/cache

A thin PSR-6 cache wrapper with a generic interface to various caching backends emphasising cache taggging and indexing to Redis, Memcached, PDO/SQL, APC and other adapters.

117548.2k6](/packages/apix-cache)[matthiasmullie/scrapbook

Scrapbook is a PHP cache library, with adapters for e.g. Memcached, Redis, Couchbase, APCu, SQL and additional capabilities (e.g. transactions, stampede protection) built on top.

3232.8M45](/packages/matthiasmullie-scrapbook)[jamm/memory

Key-value storage in memory. As a storage can be used: APC, Redis, Memcache, Shared memory. All storage objects have one interface, so you can switch them without changing the working code. Contains PHP Redis client.

13327.0k1](/packages/jamm-memory)[desarrolla2/cache

Provides an cache interface for several adapters Apc, Apcu, File, Mongo, Memcache, Memcached, Mysql, Mongo, Redis is supported.

1342.5M48](/packages/desarrolla2-cache)[arvenil/ninja-mutex

Simple to use mutex implementation that can use flock, memcache, memcached, mysql or redis for locking

1963.8M30](/packages/arvenil-ninja-mutex)

PHPackages © 2026

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