PHPackages                             dima-bzz/fork - 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. dima-bzz/fork

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

dima-bzz/fork
=============

A lightweight solution for running code concurrently in PHP

1.1.2(4y ago)011MITPHPPHP ^7.4|^8.0

Since Apr 23Pushed 4y agoCompare

[ Source](https://github.com/dima-bzz/fork)[ Packagist](https://packagist.org/packages/dima-bzz/fork)[ Docs](https://github.com/dima-bzz/fork)[ GitHub Sponsors](https://github.com/spatie)[ RSS](/packages/dima-bzz-fork/feed)WikiDiscussions main Synced 1mo ago

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

A lightweight solution for running PHP code concurrently
========================================================

[](#a-lightweight-solution-for-running-php-code-concurrently)

[![Latest Version on Packagist](https://camo.githubusercontent.com/7f717fca33033ce55ac7815bfcb15d25b2914410225e6ed3e71c9b3bb9500327/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f64696d612d627a7a2f666f726b)](https://packagist.org/packages/dima-bzz/fork)[![Tests](https://github.com/dima-bzz/fork/actions/workflows/run-tests.yml/badge.svg)](https://github.com/dima-bzz/fork/actions/workflows/run-tests.yml)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/0c4dac41292c04ed61e2bed79da6ae2c14896d4fca73c522b068170d03d1adb0/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f776f726b666c6f772f7374617475732f64696d612d627a7a2f666f726b2f436865636b253230262532306669782532307374796c696e673f6c6162656c3d636f64652532307374796c65)](https://github.com/dima-bzz/fork/actions?query=workflow%3A%22Check+%26+fix+styling%22+branch%3Amaster)[![Total Downloads](https://camo.githubusercontent.com/74fb36bfab9bb2cb73e54000d045b973fa0fb0af85d90f18f7e4e4a8f5714a18/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f64696d612d627a7a2f666f726b)](https://packagist.org/packages/dima-bzz/fork)

This package makes it easy to run PHP concurrently. Behind the scenes, concurrency is achieved by forking the main PHP process to one or more child tasks.

In this example, where we are going to call an imaginary slow API, all three closures will run at the same time.

```
use Spatie\Fork\Fork;

$results = Fork::new()
    ->run(
        fn () => (new Api)->fetchData(userId: 1),
        fn () => (new Api)->fetchData(userId: 2),
        fn () => (new Api)->fetchData(userId: 3),
    );

$results[0]; // fetched data of user 1
$results[1]; // fetched data of user 2
$results[2]; // fetched data of user 3
```

How it works under the hood
---------------------------

[](#how-it-works-under-the-hood)

✨ In this [video on YouTube](https://www.youtube.com/watch?v=IJXzc46MFPM), we explain how the package works internally.

Support us
----------

[](#support-us)

[![](https://camo.githubusercontent.com/9247b05673702934b02eea3db08aa8c0350e86ae0fc6af9c7985560268ccaf09/68747470733a2f2f6769746875622d6164732e73332e65752d63656e7472616c2d312e616d617a6f6e6177732e636f6d2f666f726b2e6a70673f743d31)](https://spatie.be/github-ad-click/fork)

We invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can support us by [buying one of our paid products](https://spatie.be/open-source/support-us).

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on [our contact page](https://spatie.be/about-us). We publish all received postcards on [our virtual postcard wall](https://spatie.be/open-source/postcards).

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

[](#requirements)

This package requires PHP 7.4 or upper and the [pcntl](https://www.php.net/manual/en/intro.pcntl.php) extensions which is installed in many Unix and Mac systems by default.

❗️ [pcntl](https://www.php.net/manual/en/intro.pcntl.php) only works in CLI processes, not in a web context.

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

[](#installation)

You can install the package via composer:

```
composer require dima-bzz/fork
```

Usage
-----

[](#usage)

You can pass as many closures as you want to `run`. They will be run concurrently. The `run` function will return an array with the return values of the executed closures.

```
use Spatie\Fork\Fork;

$results = Fork::new()
    ->run(
        function ()  {
            sleep(1);

            return 'result from task 1';
        },
        function ()  {
            sleep(1);

            return 'result from task 2';
        },
        function ()  {
            sleep(1);

            return 'result from task 3';
        },
    );

// this code will be reached this point after 1 second
$results[0]; // contains 'result from task 1'
$results[1]; // contains 'result from task 2'
$results[2]; // contains 'result from task 3'
```

### Running code before and after each closure

[](#running-code-before-and-after-each-closure)

If you need to execute some code before or after each callable passed to `run`, you can pass a callable to `before` or `after` methods. This callable passed will be executed in the child process right before or after the execution of the callable passed to `run`.

### Using `before` and `after` in the child task

[](#using-before-and-after-in-the-child-task)

Here's an example where we are going to get a value from the database using a Laravel Eloquent model. In order to let the child task use the DB, it is necessary to reconnect to the DB. The closure passed to `before` will run in both child tasks that are created for the closures passed to `run`.

```
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Spatie\Fork\Fork;

 Fork::new()
    ->before(fn () => DB::connection('mysql')->reconnect())
    ->run(
        fn () => User::find(1)->someLongRunningFunction(),
        fn () => User::find(2)->someLongRunningFunction(),
    );
```

If you need to perform some cleanup in the child task after the callable has run, you can use the `after` method on a `Spatie\Fork\Fork` instance.

### Using `before` and `after` in the parent task.

[](#using-before-and-after-in-the-parent-task)

If you need to let the callable passed to `before` or `after` run in the parent task, then you need to pass that callable to the `parent` argument.

```
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Spatie\Fork\Fork;

 Fork::new()
    ->before(
        parent: fn() => echo 'this runs in the parent task'
    )
    ->run(
        fn () => User::find(1)->someLongRunningFunction(),
        fn () => User::find(2)->someLongRunningFunction(),
    );
```

You can also pass different closures, to be run in the child and the parent task

```
use Spatie\Fork\Fork;

Fork::new()
    ->before(
        child: fn() => echo 'this runs in the child task',
        parent: fn() => echo 'this runs in the parent task',
    )
    ->run(
        fn () => User::find(1)->someLongRunningFunction(),
        fn () => User::find(2)->someLongRunningFunction(),
    );
```

### Returning data

[](#returning-data)

All output data is gathered in an array and available as soon as all children are done. In this example, `$results` will contain three items:

```
$results = Fork::new()
    ->run(
        fn () => (new Api)->fetchData(userId: 1),
        fn () => (new Api)->fetchData(userId: 2),
        fn () => (new Api)->fetchData(userId: 3),
    );
```

The output is also available in the `after` callbacks, which are called whenever a child is done and not at the very end:

```
$results = Fork::new()
    ->after(
        child: fn (int $i) => echo $i, // 1, 2 and 3
        parent: fn (int $i) => echo $i, // 1, 2 and 3
    )
    ->run(
        fn () => 1,
        fn () => 2,
        fn () => 3,
    );
```

Finally, return values from child tasks are serialized using PHP's built-in `serialize` method. This means that you can return anything you can normally serialize in PHP, including objects:

```
$result = Fork::new()
    ->run(
        fn () => new DateTime('2021-01-01'),
        fn () => new DateTime('2021-01-02'),
    );
```

### Configuring concurrency

[](#configuring-concurrency)

By default, all callables will be run in parallel. You can however configure a maximum amount of concurrent processes:

```
$results = Fork::new()
    ->concurrent(2)
    ->run(
        fn () => 1,
        fn () => 2,
        fn () => 3,
    );
```

In this case, the first two functions will be run immediately and as soon as one of them finishes, the last one will start as well.

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](.github/CONTRIBUTING.md) for details.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

Credits
-------

[](#credits)

- [Brent Roose](https://github.com/brendt)
- [Freek Van der Herten](https://github.com/freekmurze)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

27

—

LowBetter than 49% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity5

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity63

Established project with proven stability

 Bus Factor1

Top contributor holds 50.9% 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 ~26 days

Recently: every ~58 days

Total

10

Last Release

1609d ago

Major Versions

0.0.5 → 1.0.02021-04-28

PHP version history (3 changes)0.0.1PHP ^8.0

1.1.1PHP ^7.4

1.1.2PHP ^7.4|^8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/64298b29d89d10df9f5aa0c705a7770968293a0c98d3e97a8bcff75fccaf092f?d=identicon)[dima-bzz](/maintainers/dima-bzz)

---

Top Contributors

[![freekmurze](https://avatars.githubusercontent.com/u/483853?v=4)](https://github.com/freekmurze "freekmurze (58 commits)")[![brendt](https://avatars.githubusercontent.com/u/6905297?v=4)](https://github.com/brendt "brendt (35 commits)")[![dima-bzz](https://avatars.githubusercontent.com/u/8027583?v=4)](https://github.com/dima-bzz "dima-bzz (18 commits)")[![chapeupreto](https://avatars.githubusercontent.com/u/834048?v=4)](https://github.com/chapeupreto "chapeupreto (2 commits)")[![nexxai](https://avatars.githubusercontent.com/u/4316564?v=4)](https://github.com/nexxai "nexxai (1 commits)")

---

Tags

spatieforkdima-bzz

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/dima-bzz-fork/health.svg)

```
[![Health](https://phpackages.com/badges/dima-bzz-fork/health.svg)](https://phpackages.com/packages/dima-bzz-fork)
```

###  Alternatives

[spatie/fork

A lightweight solution for running code concurrently in PHP

1.0k2.6M39](/packages/spatie-fork)[spatie/laravel-package-tools

Tools for creating Laravel packages

935125.5M7.0k](/packages/spatie-laravel-package-tools)[spatie/laravel-data

Create unified resources and data transfer objects

1.7k28.9M627](/packages/spatie-laravel-data)[spatie/laravel-analytics

A Laravel package to retrieve Google Analytics data.

3.2k5.7M57](/packages/spatie-laravel-analytics)[spatie/macroable

A trait to dynamically add methods to a class

72659.6M64](/packages/spatie-macroable)[spatie/regex

A sane interface for php's built in preg\_\* functions

1.1k17.1M59](/packages/spatie-regex)

PHPackages © 2026

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