PHP Fibers: patterns I actually use outside frameworks
Fibers landed in PHP 8.1 but most discussion is about how frameworks use them internally. What are useful patterns for application code?
I am writing a CLI tool that needs to do parallel HTTP requests. Considering Fibers vs just using curl_multi.
curl_multi is fine and battle-tested. Fibers do not add much on top of it unless you want to compose async operations in a readable way. The real value of Fibers is that you can write code that looks synchronous but suspends at IO points, which is more readable than callback chains.
For a CLI tool doing parallel requests I would reach for ReactPHP or Amp before rolling my own Fiber scheduler. They handle the event loop, error propagation, and cancellation. Fibers are the primitive; the libraries are the usable abstraction.
One practical Fiber pattern for CLI: a simple cooperative scheduler. Create one Fiber per task, run each until it suspends, continue others. No external dependencies and works for CPU-light IO-heavy workloads.
Amp v3 is built on Fibers and the API is clean. Worth looking at for async CLI work. The HTTP client in Amp handles concurrent requests naturally.
I tried to implement a Fiber scheduler from scratch. Got it working but error handling and cleanup on exceptions is subtle. The edge cases are not obvious. Unless you need zero dependencies, use a library.
That is a fair point. The resume/throw interaction between fibers and the suspend point is not trivial to get right. ReactPHP promise chains are verbose but the error semantics are explicit.