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

ActiveLibrary[Caching](/categories/caching)

h4kuna/critical-cache
=====================

Only one process can to write or to delete to cache.

v2.0.1(5mo ago)16.5k↑96.4%1MITPHPPHP &gt;=8.2CI passing

Since Feb 2Pushed 5mo ago1 watchersCompare

[ Source](https://github.com/h4kuna/critical-cache)[ Packagist](https://packagist.org/packages/h4kuna/critical-cache)[ Fund](https://revolut.me/milan2m/czk1000/critical-cache)[ GitHub Sponsors](https://github.com/h4kuna)[ RSS](/packages/h4kuna-critical-cache/feed)WikiDiscussions main Synced yesterday

READMEChangelog (3)Dependencies (13)Versions (18)Used By (1)

Critical cache
==============

[](#critical-cache)

[![Downloads this Month](https://camo.githubusercontent.com/feb16545abed889678265bdf908745b0392400fb3f7efd6a3f4f6dd58fa7d1b5/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f646d2f68346b756e612f637269746963616c2d63616368652e737667)](https://packagist.org/packages/h4kuna/critical-cache)[![Latest stable](https://camo.githubusercontent.com/99c2cb91d047a3d0558536ca36fdfc6975d33716dd7f3ed957a48b46f8eabe6c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f68346b756e612f637269746963616c2d63616368652e737667)](https://packagist.org/packages/h4kuna/critical-cache)

The library extends PSR-16 about locking when write or delete to cache.

### Installation to project

[](#installation-to-project)

```
composer require h4kuna/critical-cache
```

Optional

```
composer require h4kuna/dir malkusch/lock nette/caching beste/clock
```

### How to use

[](#how-to-use)

First time you can use prepared factory [CacheFactory](./src/CacheFactory.php). The factory tell you what dependency missing. The dependency are not mandatory, because everything can be replaced by your implementation.

```
use h4kuna\CriticalCache\PSR16\Locking\CacheLockingFactory;
$cacheFactory = new CacheLockingFactory('/my/temp');
$cache = $cacheFactory->create();
assert($cache instanceof Psr\SimpleCache\CacheInterface);

$data = $cache->load('foo', fn() => 'done');
echo $data; // done
```

Method `load` try read from cache, if data is not `null` that success else create critical section by lock system (Mutex), try read from cache, because any parallel process could be faster, if is success unlock critical section and return data, else call callback for create cache, save data to cache and unlock and return data.

Pool
----

[](#pool)

Support to use multi-level cache implements CacheInterface. By order Memory -&gt; Filesystem.

```
use h4kuna\CriticalCache\PSR16\Locking\CacheLockingFactory;
use h4kuna\CriticalCache\PSR16\Pool\CachePoolFactory;

$cacheFactory = new CacheLockingFactory('/my/temp');
$cachePoolFactory = new CachePoolFactory($cacheFactory);

$cache = $cachePoolFactory->create(); // by default create MemoryCache and FileSystem. You can choose redis, memcache.
$cache->set('foo', 1); // write to memory and filesystem

$cache1 = $cachePoolFactory->create();

// try to load from Memory (not found), second is Filesystem (found), and save to Memory, return result.
echo $cache1->get('foo'); // 1
```

Lock
----

[](#lock)

By default, is used [malkusch/lock](//github.com/php-lock/lock), but if you implement [Lock](src/Lock/Lock.php) interface you can use different library.

And by default is used [FlockMutex](//github.com/php-lock/lock/blob/master/classes/mutex/FlockMutex.php) this is reason why is need [h4kuna/dir](//github.com/h4kuna/dir). If you use different [Lock](//github.com/php-lock/lock/tree/master/classes/mutex) you don't need previous library.

Cache
-----

[](#cache)

By default, is used [nette/caching](//github.com/nette/caching) with PSR16 adapter.

Clock PSR-20
------------

[](#clock-psr-20)

internal cache system beste/clock

Services
========

[](#services)

[UseOneTimeService](src/Services/UseOneTimeService.php)
-------------------------------------------------------

[](#useonetimeservice)

The service is usable for token and use one time.

```
/** @var \h4kuna\CriticalCache\Services\UseOneTimeService $useOneTimeService */
$timeToLive = 900; // seconds
$useOneTimeService->set('foo', 'token', $timeToLive);
// after 900 seconds or one call $useOneTimeService::get() is removed from cache

$useOneTimeService->get('foo'); // token
$useOneTimeService->get('foo'); // null
```

[ValidityAwareCache](src/Caching/ValidityAwareCache.php)
--------------------------------------------------------

[](#validityawarecache)

The service tell you if anything is valid, you can choose date range for valid window.

```
/** @var \h4kuna\CriticalCache\Caching\ValidityAwareCache $ValidityAwareCache */
$ValidityAwareCache->set('foo', new DateTime('tomorrow midnight')); // from is null it is mean now
$ValidityAwareCache->isValid('foo'); // true from 'now' to 'tomorrow midnight'
$ValidityAwareCache->value('foo'); // return empty string if is valid and null if is invalid
$ValidityAwareCache->from('foo'); // null mean unlimited or DateTimeImmutable
$ValidityAwareCache->to('foo'); // null mean does not exist or DateTimeImmutable
$ValidityAwareCache->isValid('foo'); // true the time is in range, false is out of range

$ValidityAwareCache->set('bar', new DateTime('tomorrow midnight'), new DateTime('+5 minutes'), 'lorem'); // the string 'lorem' it will be a valid after 5 minutes
```

[TokenService](src/Services/TokenService.php)
---------------------------------------------

[](#tokenservice)

The service generate token and keep it for defined time.

```
/** @var \h4kuna\CriticalCache\Services\TokenService $tokenService */
$token = $tokenService->make(); // return string token by default uuid v4

dump($tokenService->isEqual($token)); // true / false

// if you want compare your self let use get()
$token = $tokenService->make(value: 'lorem');
$value = $tokenService->get($token); // lorem

$tokenService->isEqual(value: $value); // false because you use get()
```

[UniqueHashQueueService](src/Services/UniqueHashQueueService.php)
-----------------------------------------------------------------

[](#uniquehashqueueservice)

The service generate unique values, witch check mechanism with source for example, with database. Create lock for critical section get one unique values from queue.

For example, we use [RandomGeneratorMock](tests/src/Mock/RandomGeneratorMock.php), the class generate alphabet, A, B, C, D ... Z, AA...

```
// implement UniqueValueServiceInterface or extends UniqueValueServiceAbstract
$checkUniqueValue = new class extends \h4kuna\CriticalCache\Services\UniqueValueServiceAbstract {

    public function __construct()
    {
        parent::__construct(new \h4kuna\CriticalCache\Tests\Mock\RandomGeneratorMock());
    }

    public function check(array $data): iterable {
        // example: $data = ['A', 'B', 'C', 'D', 'E'];
        // SELECT unique_column FROM foo WHERE unique_column IN ('A', 'B', 'C');
        // return matched values, for example B, C

        yield 'B';
        yield 'C';
        // or
        return ['B', 'C'];
    }

};

/** @var \h4kuna\CriticalCache\Services\UniqueHashQueueService $uniqueHash */
$value = $uniqueHash->execute($checkUniqueValue); // random unique value, A
$value = $uniqueHash->execute($checkUniqueValue); // random unique value, D
$value = $uniqueHash->execute($checkUniqueValue); // random unique value, E
```

[PauseAfterUse](src/Services/PauseAfterUse.php)
-----------------------------------------------

[](#pauseafteruse)

The service generate value, and sleep few seconds before allow next to generate value.

```
/** @var \h4kuna\CriticalCache\Services\PauseAfterUse $pauseAfterUse */
/** @var \Psr\Clock\ClockInterface $clock */
$pauseService = new class ($clock, 3) extends PauseService {
    protected function run(): void
    {
        var_dump('hello');
    }
};

$pauseAfterUse->execute($pauseService); // execute run()
$pauseAfterUse->execute($pauseService); // sleep 3 seconds and execute run()
```

###  Health Score

47

—

FairBetter than 93% of packages

Maintenance72

Regular maintenance activity

Popularity25

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity67

Established project with proven stability

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

Recently: every ~101 days

Total

15

Last Release

161d ago

Major Versions

v0.1.6 → v1.0.02024-08-28

v1.0.5 → v2.0.02026-01-21

PHP version history (2 changes)v0.1.0PHP &gt;=8.0

v1.0.1PHP &gt;=8.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/54b4efb9b89167fa3598b1a41477b20387390f4a0fb65b447bd6bb7c30a49020?d=identicon)[h4kuna](/maintainers/h4kuna)

---

Top Contributors

[![h4kuna](https://avatars.githubusercontent.com/u/335722?v=4)](https://github.com/h4kuna "h4kuna (48 commits)")

###  Code Quality

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

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

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

###  Alternatives

[symfony/symfony

The Symfony PHP framework

31.4k87.2M2.2k](/packages/symfony-symfony)[flow-php/flow

PHP ETL - Extract Transform Load - Data processing framework

85036.3k](/packages/flow-php-flow)[flow-php/etl

PHP ETL - Extract Transform Load - Abstraction

378604.0k104](/packages/flow-php-etl)[tempest/framework

The PHP framework that gets out of your way.

2.2k34.4k15](/packages/tempest-framework)[laminas/laminas-cache

Caching implementation with a variety of storage options, as well as codified caching strategies for callbacks, classes, and output

1077.3M154](/packages/laminas-laminas-cache)[moonshine/moonshine

Laravel administration panel

1.3k253.1k81](/packages/moonshine-moonshine)

PHPackages © 2026

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