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

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

spatie/fork
===========

A lightweight solution for running code concurrently in PHP

1.2.5(1y ago)1.0k2.6M—0.1%10320MITPHPPHP ^8.0CI passing

Since Apr 23Pushed 1mo ago15 watchersCompare

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

READMEChangelog (10)Dependencies (4)Versions (19)Used By (20)

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

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

[![Latest Version on Packagist](https://camo.githubusercontent.com/d8738202250df351384b7d9f98d2a60671d7c4f5639936740d05971d8441dffe/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7370617469652f666f726b2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/fork)[![Tests](https://github.com/spatie/fork/actions/workflows/run-tests.yml/badge.svg)](https://github.com/spatie/fork/actions/workflows/run-tests.yml)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/7baf793caa0805d90d528f0aeb8d75be5301af85890e573d63a9d29124cfe688/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f7370617469652f666f726b2f7068702d63732d66697865722e796d6c3f6c6162656c3d636f64652532307374796c65)](https://github.com/spatie/fork/actions/workflows/php-cs-fixer.yml)[![Total Downloads](https://camo.githubusercontent.com/9c264f3a6da84569f55931b8849766b23ad830b0e64287007e6a1794043619bc/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7370617469652f666f726b2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/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 8 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. ❗️ [posix](https://www.php.net/manual/en/book.posix.php) required for correct handling of process termination for Alpine Linux.

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

[](#installation)

You can install the package via composer:

```
composer require spatie/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](https://github.com/spatie/.github/blob/main/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

64

—

FairBetter than 99% of packages

Maintenance71

Regular maintenance activity

Popularity67

Solid adoption and visibility

Community42

Growing community involvement

Maturity65

Established project with proven stability

 Bus Factor1

Top contributor holds 57.2% 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 ~91 days

Recently: every ~129 days

Total

17

Last Release

390d ago

Major Versions

0.0.5 → 1.0.02021-04-28

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/7535935?v=4)[Spatie](/maintainers/spatie)[@spatie](https://github.com/spatie)

---

Top Contributors

[![freekmurze](https://avatars.githubusercontent.com/u/483853?v=4)](https://github.com/freekmurze "freekmurze (99 commits)")[![brendt](https://avatars.githubusercontent.com/u/6905297?v=4)](https://github.com/brendt "brendt (40 commits)")[![zKoz210](https://avatars.githubusercontent.com/u/28255085?v=4)](https://github.com/zKoz210 "zKoz210 (7 commits)")[![AdrianMrn](https://avatars.githubusercontent.com/u/12762044?v=4)](https://github.com/AdrianMrn "AdrianMrn (5 commits)")[![alexmanase](https://avatars.githubusercontent.com/u/10696975?v=4)](https://github.com/alexmanase "alexmanase (5 commits)")[![puggan](https://avatars.githubusercontent.com/u/866668?v=4)](https://github.com/puggan "puggan (2 commits)")[![stevebauman](https://avatars.githubusercontent.com/u/6421846?v=4)](https://github.com/stevebauman "stevebauman (2 commits)")[![AlexVanderbist](https://avatars.githubusercontent.com/u/6287961?v=4)](https://github.com/AlexVanderbist "AlexVanderbist (2 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)")[![obelloc](https://avatars.githubusercontent.com/u/9536475?v=4)](https://github.com/obelloc "obelloc (1 commits)")[![saurabhsharma2u](https://avatars.githubusercontent.com/u/41580629?v=4)](https://github.com/saurabhsharma2u "saurabhsharma2u (1 commits)")[![SidRoberts](https://avatars.githubusercontent.com/u/1364214?v=4)](https://github.com/SidRoberts "SidRoberts (1 commits)")[![yabooodya](https://avatars.githubusercontent.com/u/22002735?v=4)](https://github.com/yabooodya "yabooodya (1 commits)")[![ahmadreza1383](https://avatars.githubusercontent.com/u/61243238?v=4)](https://github.com/ahmadreza1383 "ahmadreza1383 (1 commits)")[![henzeb](https://avatars.githubusercontent.com/u/15928532?v=4)](https://github.com/henzeb "henzeb (1 commits)")[![jchambon-equativ](https://avatars.githubusercontent.com/u/207558199?v=4)](https://github.com/jchambon-equativ "jchambon-equativ (1 commits)")[![jochem-blok](https://avatars.githubusercontent.com/u/177307307?v=4)](https://github.com/jochem-blok "jochem-blok (1 commits)")

---

Tags

asyncconcurrentperformancephpspatiefork

###  Code Quality

TestsPest

### Embed Badge

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

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

###  Alternatives

[spatie/laravel-package-tools

Tools for creating Laravel packages

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

Create unified resources and data transfer objects

1.8k28.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

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

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

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

PHP Enums

84529.1M68](/packages/spatie-enum)

PHPackages © 2026

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