
After you've created all three fibers, you'd loop over them, and resume them one by one. You would create one fiber for each request, and pause the fiber after the request is sent. It was already possible by using generators and yield, but fibers are a significant improvement, since they are specifically designed for this use case. You can see how such an approach reduces execution time because we're using the waiting time more optimally.įibers are a new mechanism in PHP 8.1 that allow you to manage those parallel execution paths more efficiently. If that's the case we can process it immediately. And while waiting we periodically check whether one of our requests is already finished. Then we send the next request, followed by another. In the world of parallel processing, we send the request but don't wait. This is a synchronous execution flow: send, wait, process, repeat.

It's only when the response arrives that we can work again.
Listen later stitcher download code#
The coloured pieces of each request represent PHP code actually running, where the CPU on your server is doing work, the transparent blocks represent waiting times: the request needs to be sent over the wire, the other server needs to process it and send it back. You need to read this chart from the top down, and time progresses the further down you go. Let's represent such a program flow with as easy a chart as possible. The synchronous way of doing so is by sending the first one, waiting for the response, then sending the second one, waiting, etc. Imagine you want to send three HTTP requests and process their combined result.

So instead of going down this path and make things way too complicated, we'll discuss what fibers are conceptually, why they are barely usable in application code, and how you can make use of async PHP after all.
