Introducing

PHP 8.1 - Fibers


Fibers are a new mechanism in PHP 8.1

that allow you to manage those parallel execution paths more efficiently. It was already possible by using generators and yield, but fibers are a significant improvement, since they are specifically designed for this use case.

On the one hand, fibers are a great addition to PHP: a low-level way of creating green threads (I'll clarify what that's about, hang on). On the other hand, chances are rather slim that you'll ever use them in your project: they are a low-level component, and will only be used on libraries that deal with asynchronicity.

Nevertheless, it's worth talking about them.

Fibers are a way to handle parallel processing within the same physical process.

There aren't actual multiple threads or parallel processes when using fibers, meaning that there will never be parts of your code that are running at the _same_ time, but they _do_ allow developers to do other things, while parts of your code are waiting. For example: when a part of your code is waiting for a file to be read, you could do already start fetching another file.

Imagine fibers being used in a loop, and now you have a way to handle async I/O in a much more efficient way. Say you'd send 10 HTTP requests, and wait for all of them to finish at once, instead of sending and waiting for them one by one.

Fibers allow you to do exactly that, in an elegant way; because, technically, this was already possible to do without them (by using generators and yield), though Fibers offer an explicit and easier-to-use API.

The flip side of the coin with fibers is that there aren't suddenly any _more_ ways to do asynchronous I/O in PHP. In fact, there only are a couple of low-level functions that allow PHP to continue its execution while I/O waits are handled behind the scenes.

If you're really curious: there's pcntl_async_signals and socket_select, and that's about it.

So, fibers are a welcome addition, but if you see someone claiming that "PHP 8.1 is async now", then you should know those claims are false. PHP isn't any more "async" then it was before 8.1: there are a few functions that allow for async I/O waiting, and fibers only offer a cleaner API to handle such code.

Categories:
Tags:
PHP 8.1
PHP 8.1 Fibers