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.

<span class="hljs-keyword">use</span> <span class="hljs-title">Spatie</span><span class="hljs-title">Fork</span><span class="hljs-title">Fork</span>;
<p>$results = Fork::new()
->run(
fn () => (<span class="hljs-keyword">new</span> Api)->fetchData(userId: <span class="hljs-number">1</span>),
fn () => (<span class="hljs-keyword">new</span> Api)->fetchData(userId: <span class="hljs-number">2</span>),
fn () => (<span class="hljs-keyword">new</span> Api)->fetchData(userId: <span class="hljs-number">3</span>),
);</p>
<p>$results[<span class="hljs-number">0</span>]; <span class="hljs-comment">// fetched data of user 1</span>
$results[<span class="hljs-number">1</span>]; <span class="hljs-comment">// fetched data of user 2</span>
$results[<span class="hljs-number">2</span>]; <span class="hljs-comment">// fetched data of user 3</span>
</p>

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.

Categories: PHP