5

A lightweight solution for running PHP code concurrently

 3 years ago
source link: https://freek.dev/1973-a-lightweight-solution-for-running-php-code-concurrently
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

A lightweight solution for running PHP code concurrently

Original – May 3rd 2021 by Freek Van der Herten – 1 minute read

Our team released a new package called spatie/fork. Using this package you can easily execute multiple pieces of code concurrently.

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

If you want to know more about why we created the package, check out this blogpost by my colleague Brent.

In the video below, which was streamed live, you can see me explain the internals.

To know more about how to use the package, head over to the readme of spatie/fork on GitHub.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK