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

ActiveLibrary[Caching](/categories/caching)

matomo/cache
============

PHP caching library based on Doctrine cache

3.0.0(4mo ago)38854.1k↓11.7%15[2 issues](https://github.com/matomo-org/component-cache/issues)3LGPL-3.0PHPPHP &gt;=7.2CI passing

Since Dec 15Pushed 3mo ago13 watchersCompare

[ Source](https://github.com/matomo-org/component-cache)[ Packagist](https://packagist.org/packages/matomo/cache)[ RSS](/packages/matomo-cache/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (2)Versions (27)Used By (3)

Matomo/Cache
============

[](#matomocache)

This is a PHP caching library based on [Doctrine cache](https://github.com/doctrine/cache) that supports different backends. At [Matomo](https://matomo.org) we developed this library with the focus on speed as we make heavy use of caching and sometimes fetch hundreds of entries from the cache in one request.

[![Build Status](https://camo.githubusercontent.com/c29f5d846f8e0e255402f4e06af8842f847ff44aecd413a63e18ec0dd380fbda/68747470733a2f2f7472617669732d63692e636f6d2f6d61746f6d6f2d6f72672f636f6d706f6e656e742d63616368652e7376673f6272616e63683d6d6173746572)](https://travis-ci.com/matomo-org/component-cache)

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

[](#installation)

With Composer:

```
{
    "require": {
        "matomo/cache": "*"
    }
}
```

Supported backends
------------------

[](#supported-backends)

- Array (holds cache entries only during one request but is very fast)
- Null (useful for development, won't cache anything)
- File (stores the cache entry on the file system)
- Redis (stores the cache entry on a Redis server, requires [phpredis](https://github.com/nicolasff/phpredis))
- Chained (allows to chain multiple backends to make sure it will read from a fast cache if possible)
- DefaultTimeout and KeyPrefix can be used to wrap other backend with default parameters.

Doctrine cache provides support for many more backends and adding one of those is easy. For example:

- APC
- Couchbase
- Memcache
- MongoDB
- Riak
- WinCache
- Xcache
- ZendData

Please send a pull request in case you have added one.

Different caches
----------------

[](#different-caches)

This library comes with three different types of caches. The naming is not optimal right now.

### Lazy

[](#lazy)

This can be considered as the default cache to use in case you don't know which one to pick. The lazy cache works with any backend so you can decide whether you want to persist cache entries between requests or not. It does not support the caching of any objects. Only boolean, numbers, strings and arrays are supported. Whenever you request an entry from the cache it will fetch the entry from the defined backend again which can cause many reads depending on your application.

### Eager

[](#eager)

This cache stores all its cache entries under one "cache" entry in a configurable backend.

This comes handy for things that you need very often, nearly in every request. Instead of having to read eg. a hundred cache entries from files it only loads one cache entry which contains the hundred keys. Should be used only for things that you need very often and only for cache entries that are not too large to keep loading and parsing the single cache entry fast. This cache is even more useful in case you are using a slow backend such as a file or a database. Instead of having a hundred stat calls there will be only one. All cache entries it contains have the same life time. For fast performance it won't validate any cache ids. It is not possible to cache any objects using this cache.

### Transient

[](#transient)

This class is used to cache any data during one request. It won't be persisted.

All cache entries will be cached in a simple array meaning it is very fast to save and fetch cache entries. You can basically achieve the same by using a lazy cache and a backend that does not persist any data such as the array cache but this one will be a bit faster as it won't validate any cache ids and it allows you to cache any kind of objects. Compared to the lazy cache it does not support setting any life time as it will be only valid during one request anyway. Use this one if you read hundreds or thousands of cache entries and if performance really matters to you.

Usage
-----

[](#usage)

### Creating a file backend

[](#creating-a-file-backend)

```
$options = array('directory' => '/path/to/cache');
$factory = new \Matomo\Cache\Backend\Factory();
$backend = $factory->buildBackend('file', $options);
```

### Creating a Redis backend

[](#creating-a-redis-backend)

```
$options = array(
    'host'     => '127.0.0.1',
    'port'     => '6379',
    'timeout'  => 0.0,
    'database' => 15, // optional
    'password' => 'secret', // optional
);
$factory = new \Matomo\Cache\Backend\Factory();
$backend = $factory->buildBackend('redis', $options);
```

### Creating a chained backend

[](#creating-a-chained-backend)

```
$options = array(
    'backends' => array('array', 'file'),
    'file'     => array('directory' => '/path/to/cache')
);
$factory = new \Matomo\Cache\Backend\Factory();
$backend = $factory->buildBackend('redis', $options);
```

Whenever you set a cache entry it will save it in the array and in the file cache. Whenever you are trying to read a cache entry it will first try to get it from the fast array cache. In case it is not available there it will try to fetch the cache entry from the file system. If the cache entry exists on the file system it will cache the entry automatically using the array cache so the next read within this request will be fast and won't cause a stat call again. If you delete a cache entry it will be removed from all configured backends. You can chain any backends. It is recommended to list faster backends first.

### Creating a decorated backend with `DefaultTimeout` or `KeyPrefix`

[](#creating-a-decorated-backend-with-defaulttimeout-or-keyprefix)

```
$options = array(
    'backend'   => 'array',
    'array'     => array(),
    'keyPrefix' => 'someKeyPrefixStr'
);
$factory = new \Matomo\Cache\Backend\Factory();
$backend = $factory->buildBackend('keyPrefix', $options);
```

Sometimes its useful to set default a default parameter for the timeout to force prevent infinite lifetimes, or to specify a key prefix to prevent different versions of the app from reading and writing the same cache entry.
`DefaultTimeout` and `KeyPrefix` are "decorators" that wrap another backend. Currently each takes a single configuration argument with the same name as the backend.

backendargumentdescriptionDefaultTimeout`defaultTimeout`Uses the `integer` value as the default timeout for defining cache entry lifetime. Only comes to effect when no lifetime is specified; Prevents infinite lifetimes.KeyPrefix`keyPrefix`Prefixes the given value to the keys for any operation. For example `'Key123'` would become `'SomePrefixKey123'`### Creating a lazy cache

[](#creating-a-lazy-cache)

[Description lazy cache.](#lazy)

```
$factory = new \Matomo\Cache\Backend\Factory();
$backend = $factory->buildBackend('file', array('directory' => '/path/to/cache'));

$cache = new \Matomo\Cache\Lazy($backend);
$cache->fetch('myid');
$cache->contains('myid');
$cache->delete('myid');
$cache->save('myid', 'myvalue', $lifeTimeInSeconds = 300);
$cache->flushAll();
```

### Creating an eager cache

[](#creating-an-eager-cache)

[Description eager cache.](#eager)

```
$cache = new \Matomo\Cache\Eager($backend, $storageId = 'eagercache');
$cache->fetch('myid');
$cache->contains('myid');
$cache->delete('myid');
$cache->save('myid', new \stdClass());
$cache->persistCacheIfNeeded($lifeTimeInSeconds = 300);
$cache->flushAll();
```

It will cache all set cache entries under the cache entry `eagercache`.

### Creating a transient cache

[](#creating-a-transient-cache)

[Description transient cache.](#transient)

```
$cache = new \Matomo\Cache\Transient();
$cache->fetch('myid');
$cache->contains('myid');
$cache->delete('myid');
$cache->save('myid', new \stdClass());
$cache->flushAll();
```

License
-------

[](#license)

The Cache component is released under the [LGPL v3.0](http://choosealicense.com/licenses/lgpl-3.0/).

Changelog
---------

[](#changelog)

- 0.2.5: updating to doctrine/cache 1.4 which contains our fix
- 0.2.4: do not throw exception when clearing a file cache if the cache dir doesn't exist
- 0.2.3: fixed another race condition in file cache
- 0.2.2: fixed a race condition in file cache
- 0.2.0: Initial release

###  Health Score

60

—

FairBetter than 99% of packages

Maintenance78

Regular maintenance activity

Popularity52

Moderate usage in the ecosystem

Community29

Small or concentrated contributor base

Maturity68

Established project with proven stability

 Bus Factor1

Top contributor holds 52.1% 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 ~184 days

Recently: every ~424 days

Total

23

Last Release

120d ago

Major Versions

0.2.8 → 1.0.02016-09-14

1.0.1 → 2.0.02018-02-14

1.0.2 → 2.0.22019-07-14

1.0.4 → 2.0.32021-05-26

2.0.6 → 3.0.02026-01-19

PHP version history (4 changes)0.1.0PHP &gt;=5.3.2

1.0.0PHP &gt;=5.5.9

2.0.3PHP &gt;=7.1

3.0.0PHP &gt;=7.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/80e09d9121023df96ecb1fc20edac8c3d9b724b50dbd3815fa264ae1a6adc58b?d=identicon)[matomo](/maintainers/matomo)

---

Top Contributors

[![tsteur](https://avatars.githubusercontent.com/u/273120?v=4)](https://github.com/tsteur "tsteur (49 commits)")[![sgiehl](https://avatars.githubusercontent.com/u/1579355?v=4)](https://github.com/sgiehl "sgiehl (22 commits)")[![diosmosis](https://avatars.githubusercontent.com/u/125140?v=4)](https://github.com/diosmosis "diosmosis (9 commits)")[![mattab](https://avatars.githubusercontent.com/u/466765?v=4)](https://github.com/mattab "mattab (6 commits)")[![mnapoli](https://avatars.githubusercontent.com/u/720328?v=4)](https://github.com/mnapoli "mnapoli (2 commits)")[![deees](https://avatars.githubusercontent.com/u/282701?v=4)](https://github.com/deees "deees (1 commits)")[![williamdes](https://avatars.githubusercontent.com/u/7784660?v=4)](https://github.com/williamdes "williamdes (1 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (1 commits)")[![jakeh999](https://avatars.githubusercontent.com/u/28597867?v=4)](https://github.com/jakeh999 "jakeh999 (1 commits)")[![peter279k](https://avatars.githubusercontent.com/u/9021747?v=4)](https://github.com/peter279k "peter279k (1 commits)")[![ThaDafinser](https://avatars.githubusercontent.com/u/533017?v=4)](https://github.com/ThaDafinser "ThaDafinser (1 commits)")

---

Tags

arrayrediscachefile

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[vink/nova-cache-card

Manage your application's cache from a handy Laravel Nova dashboard card.

26317.3k1](/packages/vink-nova-cache-card)[garyr/memento

Lightweight cache library

186.6k1](/packages/garyr-memento)[ihor/cachalot

Cache a lot in a proper way (APC, XCache, Memcached, Redis, Couchbase)

2528.1k](/packages/ihor-cachalot)[bnomei/kirby3-redis-cachedriver

Advanced Redis cache-driver with in-memory store, transactions and preloading

101.7k](/packages/bnomei-kirby3-redis-cachedriver)

PHPackages © 2026

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