PHPackages                             jerome/matrix - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. jerome/matrix

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

jerome/matrix
=============

Event-driven asynchronous helpers and concurrency control for ReactPHP.

3.4.0(9mo ago)6011.9k↑19.5%2[3 PRs](https://github.com/Thavarshan/matrix/pulls)2MITPHPPHP ^8.3CI passing

Since Sep 29Pushed 2w ago4 watchersCompare

[ Source](https://github.com/Thavarshan/matrix)[ Packagist](https://packagist.org/packages/jerome/matrix)[ Docs](https://thavarshan.com)[ Fund](https://www.buymeacoffee.com/thavarshan)[ GitHub Sponsors](https://github.com/thavarshan)[ RSS](/packages/jerome-matrix/feed)WikiDiscussions main Synced 2w ago

READMEChangelog (10)Dependencies (13)Versions (17)Used By (2)

Matrix
======

[](#matrix)

Matrix provides small, event-driven async helpers for [ReactPHP](https://reactphp.org/). It makes promise composition, concurrency limits, retries, timeouts, cancellation, and rate limiting consistent without pretending to create threads or process-level parallelism.

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

[](#requirements)

- PHP 8.3 or newer
- `react/event-loop` 1.6 or newer
- `react/promise` 3.3 or newer

No `pcntl`, `posix`, or `sockets` extension is required.

Install it with Composer:

```
composer require jerome/matrix
```

Core usage
----------

[](#core-usage)

Import the helpers explicitly in each file:

```
use function Matrix\Support\async;
use function Matrix\Support\await;
use function Matrix\Support\delay;

$value = await(async(fn () => 'ready'));
$later = await(delay(0.1, 'ready later'));
```

`async()` schedules a callable on the ReactPHP loop. The callable must use non-blocking I/O; `sleep()`, `file_get_contents()`, CPU-heavy work, and synchronous database clients still block the loop.

`await()` is a top-level synchronous bridge for CLI scripts and other code that owns the loop. It must not be called from inside an already-running loop callback. Use promise chaining inside an event-driven application instead.

Composition and concurrency
---------------------------

[](#composition-and-concurrency)

All combinators accept promises or plain values. `all()`, `race()`, and `any()` accept any iterable. `all()` preserves keys:

```
use function Matrix\Support\all;
use function Matrix\Support\async;
use function Matrix\Support\await;

$results = await(all([
    'first' => async(fn () => 1),
    'second' => 2,
]));
// ['first' => 1, 'second' => 2]
```

`map()` accepts arrays or generators, preserves keys, and limits active work when `$concurrency` is greater than zero. `pool()` does the same for zero-argument task callables. Both stop scheduling new work after the first failure and observe already-running tasks.

```
use function Matrix\Support\await;
use function Matrix\Support\map;

$values = await(map(
    ['a' => 1, 'b' => 2, 'c' => 3],
    fn (int $value): int => $value * 2,
    concurrency: 2,
));
```

`batch()` groups values in encounter order and flattens each batch result into a list. `waterfall()` passes each result to the next callable.

Timeouts, retries, and cancellation
-----------------------------------

[](#timeouts-retries-and-cancellation)

```
use function Matrix\Support\async;
use function Matrix\Support\await;
use function Matrix\Support\retry;
use function Matrix\Support\timeout;

$result = await(timeout(
    retry(fn () => async(fn () => fetchNonBlockingData()), 3),
    5.0,
));
```

Timeouts cancel the losing operation and their timer. Retry backoff is event-loop based. Invalid durations, limits, or attempt counts throw `InvalidArgumentException` before work is scheduled.

`cancellable()` returns a native ReactPHP `PromiseInterface`. Calling `cancel()` invokes the cleanup callback once and forwards cancellation to the wrapped promise:

```
use function Matrix\Support\cancellable;
use function Matrix\Support\delay;

$operation = cancellable(delay(30), fn () => releaseResources());
$operation->cancel();
```

Rate limiting
-------------

[](#rate-limiting)

```
use function Matrix\Support\await;
use function Matrix\Support\rateLimit;

$limited = rateLimit(fn (string $url) => fetchNonBlocking($url), 2, 1.0);
$response = await($limited('https://example.com'));
```

The limiter uses a sliding window and removes cancelled queued calls before execution.

Events and metrics
------------------

[](#events-and-metrics)

Matrix emits `promise.created`, `promise.resolved`, `promise.rejected`, and `promise.timeout` events for Matrix-created operations. Listener exceptions are isolated so an observer cannot break application work.

```
use function Matrix\Support\listen;

listen('promise.rejected', static function ($event): void {
    error_log($event->getErrorClass().': '.$event->getErrorMessage());
});
```

`metricsCollector()->getMetrics()` keeps cumulative counters and bounded timing samples. Percentiles describe the most recent 1,024 samples per operation series, so metrics remain safe in long-running workers.

Development
-----------

[](#development)

```
composer install
composer check
```

The check runs Composer validation, Pint, PHPStan at maximum level, and PHPUnit. See [UPGRADING.md](UPGRADING.md) for the 3.x to 4.0 migration notes.

License
-------

[](#license)

Matrix is released under the MIT license.

###  Health Score

53

—

FairBetter than 96% of packages

Maintenance79

Regular maintenance activity

Popularity38

Limited adoption so far

Community19

Small or concentrated contributor base

Maturity63

Established project with proven stability

 Bus Factor1

Top contributor holds 89.3% 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 ~60 days

Recently: every ~111 days

Total

12

Last Release

18d ago

Major Versions

1.0.1 → 2.0.02024-12-06

2.0.0 → 3.0.02024-12-16

3.x-dev → 4.0.0-beta.12026-07-30

PHP version history (3 changes)1.0.0PHP ^8.2

2.0.0PHP ^8.3 || ^8.4

3.3.1PHP ^8.3

### Community

Maintainers

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

---

Top Contributors

[![Thavarshan](https://avatars.githubusercontent.com/u/10804999?v=4)](https://github.com/Thavarshan "Thavarshan (50 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (3 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (3 commits)")

---

Tags

asyncfiberjavascriptmatrixnon-blockingphptask

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/jerome-matrix/health.svg)

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

###  Alternatives

[composer/composer

Composer helps you declare, manage and install dependencies of PHP projects. It ensures you have the right stack everywhere.

29.5k199.6M3.4k](/packages/composer-composer)[friendsofphp/php-cs-fixer

A tool to automatically fix PHP code style

13.5k257.0M28.0k](/packages/friendsofphp-php-cs-fixer)[ccxt/ccxt

A cryptocurrency trading API with more than 100 exchanges in JavaScript / TypeScript / Python / C# / PHP / Go

43.6k344.8k1](/packages/ccxt-ccxt)[team-reflex/discord-php

An unofficial API to interact with the voice and text service Discord.

1.1k434.3k26](/packages/team-reflex-discord-php)[rector/rector-src

Instant Upgrade and Automated Refactoring of any PHP code

136411.0k14](/packages/rector-rector-src)[react/react

ReactPHP: Event-driven, non-blocking I/O with PHP.

9.1k3.7M65](/packages/react-react)

PHPackages © 2026

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