A lightweight solution for running code concurrently in PHP

A lightweight solution for running code concurrently in PHP cover image

Spatie released a new package called Spatie/fork. This package offers you an easy way to execute multiple pieces of code simultaneously. Spatie/fork makes it easy to run PHP at the same time. Behind the scenes, concurrency is accomplished by forking the central PHP process to one or more child tasks.

Requirements

This package requires PHP 8 and the pcntl extensions.
pcntl only works in CLI processes, not in a web context.

Installation

You can install this package via composer by running this command:

composer require spatie/fork

Usage

You can pass as many closures as you want to run. They will 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'

Executing code before and after each closure

If you want 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.

Applying before and after in the child task

Here’s an example where we will get a value from the database utilizing a Laravel Eloquent model. To let the child task, we’ve to use the database. 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(),
    );

Applying before and after in the parent task

If you want to let the callable passed to before or after the execution 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(),
    );

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'),
    );

You can also configure concurrency and explore many options in this package. You can view its source code and documentation on Github. If you’re a visual learner, then you can view its complete guide on youtube.

Written by

Rizwan Aslam

Founder and CEO of CodeBrisk, with years of experience building web applications with Laravel and leading a team of expert developers.

More about Rizwan
Book a free call
Book a call with CodeBrisk