PHPackages                             thomas-institut/datacache - 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. thomas-institut/datacache

ActiveLibrary[Caching](/categories/caching)

thomas-institut/datacache
=========================

Cache abstraction and basic implementation

v1.0.1(1y ago)014GPL-3.0-or-laterPHPPHP &gt;=8.3CI passing

Since Apr 16Pushed 1y ago2 watchersCompare

[ Source](https://github.com/thomas-institut/datacache)[ Packagist](https://packagist.org/packages/thomas-institut/datacache)[ RSS](/packages/thomas-institut-datacache/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)Dependencies (2)Versions (3)Used By (0)

DataCache
=========

[](#datacache)

[![Latest Stable Version](https://camo.githubusercontent.com/17e059b027cbbcd936182b4951d47061aeb4b1dfdb202e005ddc94c45943fe45/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f74686f6d61732d696e7374697475742f6461746163616368653f6c6162656c3d537461626c65)](https://camo.githubusercontent.com/17e059b027cbbcd936182b4951d47061aeb4b1dfdb202e005ddc94c45943fe45/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f74686f6d61732d696e7374697475742f6461746163616368653f6c6162656c3d537461626c65)[![Test](https://github.com/thomas-institut/datacache/actions/workflows/php.yml/badge.svg?branch=main)](https://github.com/thomas-institut/datacache/actions/workflows/php.yml/badge.svg?branch=main)[![GitHub License](https://camo.githubusercontent.com/0c414c46382027742fdaf8645e107db771d3d2f272f7b61d3e93e68fd7828b8c/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f74686f6d61732d696e7374697475742f646174616361636865)](https://camo.githubusercontent.com/0c414c46382027742fdaf8645e107db771d3d2f272f7b61d3e93e68fd7828b8c/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f74686f6d61732d696e7374697475742f646174616361636865)

[![Dynamic JSON Badge](https://camo.githubusercontent.com/819fcc3c7e70a47e2ea355a860a29f3e1d7974da7b82eb57d31abff04a65de0d/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f64796e616d69632f6a736f6e3f75726c3d68747470732533412532462532467261772e67697468756275736572636f6e74656e742e636f6d25324674686f6d61732d696e7374697475742532466461746163616368652532467265667325324668656164732532466d61696e253246636f6d706f7365722e6a736f6e2671756572793d2532342e726571756972652e706870266c6162656c3d50485025323056657273696f6e)](https://camo.githubusercontent.com/819fcc3c7e70a47e2ea355a860a29f3e1d7974da7b82eb57d31abff04a65de0d/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f64796e616d69632f6a736f6e3f75726c3d68747470732533412532462532467261772e67697468756275736572636f6e74656e742e636f6d25324674686f6d61732d696e7374697475742532466461746163616368652532467265667325324668656164732532466d61696e253246636f6d706f7365722e6a736f6e2671756572793d2532342e726571756972652e706870266c6162656c3d50485025323056657273696f6e)

This package provides an interface to a cache that can store strings. It also provides three simple, yet effective implementations.

Implementations MUST pass all tests in the included `DataCacheReferenceTest`

DataCache Interface
-------------------

[](#datacache-interface)

```
class MyDataCache implements DataCache {
// ...
}

$cache = new MyDataCache(...);
```

To cache a string with the cache's default TTL:

```
$cache->set('someKey', 'someValue');
```

There are no restrictions on the characters that can be used as a key or value: any character is allowed (including non-printable ones) and there is no set maximum length.

Implementations MUST support arbitrary characters in keys and values but MAY impose some limits to key and value lengths. Implementations MUST support maximum key lengths of at least 2048 characters and maximum value lengths of at least 32 megabytes.

Implementations decide what is the default TTL when the user has not specified one. The default TTL can be set at any time with:

```
$cache->setDefaultTtl($newDefaultTtl);
```

TTLs are given in seconds. A TTL of 0 seconds means that items will not expire. If a negative TTL is given to the `setDefaultTtl` method, no changes will be made to the current default TTL.

The default TTL can be overridden when setting a value:

```
$cache->set('someKey', 'someValue', $customTtl);
```

where `$customTtl` is given in seconds. A TTL equal to zero instructs the cache to never expire the item, while a negative TTL is ignored (and the default TTL will be used).

The value of a cached item can be retrieved with:

```
$value = $cache->get('someKey');
```

If the item is not in the cache, the `get` method will throw an `ItemNotInCacheException`.

To check if an item is in the case without necessarily retrieving it, use the following convenience method:

```
$exists = $cache->isInCache('someKey');
```

However, implementations may still have to retrieve the item to test for existence, so it cannot be generally assumed that the `isInCache` method is more efficient.

Some implementations may be able to report the remaining TTL for an item:

```
$remainingTtl = $cache->getRemainingTtl('someKey');
```

If the cache does not support reporting remaining TTLs, this method returns -1. Otherwise, it returns the number of seconds until the item's expiration or 0 if the item will never expire.

To delete an item:

```
$cache->delete('someKey');
```

The delete method returns silently if the item is not in the cache.

All the items in the cache can be deleted at once with the flush method:

```
$cache->flush();
```

Depending on the implementation, a cache flush may delete everything in the cache, including items that were stored in the same underlying storage or service by other DataCache instances or by any other means. The only mandatory behaviour is that all items set by the cache instance must not be accessible after a flush.

Some implementations may also be able to clean the cache by releasing memory or storage space for items that are already expired:

```
$cache->clean();
```

If the implementation does not support cleaning or if manual cleaning is not available for the cache, the clean method will return silently and nothing will happen.

InMemoryDataCache
-----------------

[](#inmemorydatacache)

`InMemoryDataCache` is a `DataCache` implementation that uses a PHP array to store item values.

The constructor does not have any parameters:

```
$cache = new InMemoryDataCache();
```

This cache supports arbitrary length keys and values, can report remaining TTLs and will only remove expired items from the underlying PHP array when explicitly deleted or when the `clean` or `flush` methods are called.

When the instance is destroyed, all cached items will be destroyed as well.

DirectoryDataCache
------------------

[](#directorydatacache)

`DirectoryDataCache` is a `DataCache` that stores each individual item's value in a file in a given directory. That is, every item generates one separate file that contains the value of the item. As such, the cache's content will persist after instances are destroyed, and items can be deleted manually by simply deleting their corresponding files.

```
$cache = new DirectoryDataCache('/path/to/directory', $cacheName);
```

`$cacheName` is a string that identifies the cache. It is used as a filename prefix for the files generated by the cache. This allows to have multiple independent caches in the same directory.

The file name for a cached item has the following form:

```
$directoryPath . '/' . $cacheName . $sep . $keyOrHash . $sep . $exp . '.' . $ext
```

where `$sep` is a separator character (by default `'-'`) and `$ext` is a file extension (by default `'txt'`).

By default, `$keyOrHash` is the item's key if the key does not contain the separator nor any character that the file system does not allow in file name. Otherwise, a hash of the key will be used instead.

`$exp` is the Unix timestamp after which the item is no longer valid.

The constructor has three more optional parameters to control file names:

- the file extension to use for all files (default `'txt'`). It can be empty.
- the character to use as field separator in file name (default `'-'`). The characters `*` and `/` cannot be used as separators. If the file extension is not empty, the dot cannot be used either.
- a boolean flag that instructs the cache to ALWAYS use the hash of an item's key in the file name (default `false`).

`DirectoryDataCache` supports arbitrary length keys and values, does NOT report remaining TTLs and will only delete files from disk when items are explicitly deleted or when the `clean` or `flush` methods are called.

MultiCacheDataCache
-------------------

[](#multicachedatacache)

`MultiCacheDataCache` is a `DataCache` that aggregates a list of `DataCache` instances. When an item is stored, it is stored in all caches and when it is deleted it is deleted from all caches as well. However, when an item is retrieved, it is only retrieved from the first cache in the list that has it.

The intended use of this cache is setting up faster caches in the first positions in the list and slower, perhaps persistent caches, in the latter positions. Reads will normally be handled by the faster caches, while the slower, persistent caches are used as backup.

The constructor requires an array of cache instances or callables that return a cache instance, an optional array of key prefixes to attach to keys in the corresponding caches and an optional boolean flag that when `true`, instructs the cache to use an `InMemoryDataCache` when a cache callable fails (by default this flag is `false`)

```
$cache = new MultiCacheDataCache( [ $cache1, $callable2, $cache3 ...]);

$cache2 = new MultiCacheDataCache(
    [ $cache1, $callable2, ...],
    [ 'prefix1', 'prefix2', ...], true);
```

CacheAware Interface
--------------------

[](#cacheaware-interface)

`CacheAware` is an interface that provides common functions that allow clients to control caching in the class: set the cache with an instance of a `DataCache` implementation or with a callable, start and stop using the cache and tell whether the cache is in use or not.

```
class MyCacheAware  implements CacheAware {

    public function someMethod() {

         // ...
        if ($this->isCacheInUse()) {
            // do something with the cache
            $this->getDataCache()->set(...);
        }
    }
}

$myInstance = new MyCacheWare(...);

$myInstance->setCache($someDataCacheInstanceOrSomeCallable);

$myInstance->useCache();
$myInstance->someMethod();  // cache will be used

$myInstance->doNotUseCache();
$myInstance->someMethod(); // cache will not be used
```

The trait `SimpleCacheAwareTrait` provided in this package implements this interface.

###  Health Score

31

—

LowBetter than 68% of packages

Maintenance48

Moderate activity, may be stable

Popularity6

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity53

Maturing project, gaining track record

 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 ~5 days

Total

2

Last Release

391d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/bdaa55fa14e6465a3a36c0814583c3cde96e14b6f556d01d866065d0bcb42b3e?d=identicon)[rafaelnajera](/maintainers/rafaelnajera)

---

Top Contributors

[![rafaelnajera](https://avatars.githubusercontent.com/u/17843226?v=4)](https://github.com/rafaelnajera "rafaelnajera (16 commits)")

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/thomas-institut-datacache/health.svg)

```
[![Health](https://phpackages.com/badges/thomas-institut-datacache/health.svg)](https://phpackages.com/packages/thomas-institut-datacache)
```

###  Alternatives

[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)[cheprasov/php-redis-client

Php client for Redis. It is a fast, fully-functional and user-friendly client for Redis, optimized for performance. RedisClient supports the latest versions of Redis starting from 2.6 to 6.0

1281.2M21](/packages/cheprasov-php-redis-client)[amphp/redis

Efficient asynchronous communication with Redis servers, enabling scalable and responsive data storage and retrieval.

165634.7k44](/packages/amphp-redis)

PHPackages © 2026

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