Skip to Content
Course content

156: Fibers Revisited In Depth

Click on the "Edit" button in the top corner of the screen to edit your slide content.

By now, you know that Fibers give us the ability to pause a block of code and jump back to the main execution flow. On the surface, it feels like magic. But if you're like I was when I first encountered them, your first instinct is probably to use them as a way to "multitask" manually. You create a Fiber, you suspend it when you hit a slow I/O call, and you resume it when you think it's ready. It works for a tiny script, but it's a recipe for disaster in a real application.

The Manual Orchestration Trap

The naive way to use Fibers is to treat them as individual units of work that you manage by hand. Imagine you're building a dashboard that needs to fetch data from three different third-party APIs. You might be tempted to wrap each API call in a Fiber, suspend the Fiber while the network request is pending, and then manually call $fiber->resume() in a while loop.

// The "Manual" way - don't actually do this in production
$fibers = [];
$fibers[] = new Fiber(fn() => fetchApi('https://api.a.com'));
$fibers[] = new Fiber(fn() => fetchApi('https://api.b.com'));

foreach ($fibers as $f) $f->start();

while (count($fibers) > 0) {
    foreach ($fibers as $key => $f) {
        if ($f->isTerminated()) {
            unset($fibers[$key]);
            continue;
        }
        // We're just guessing or blindly resuming
        $f->resume(); 
    }
    usleep(1000); 
}

The problem here is that you've just built a very inefficient "busy-wait" loop. You're resuming Fibers regardless of whether the data they are waiting for has actually arrived. You aren't actually gaining the benefits of non-blocking I/O; you're just adding the overhead of Fiber context switching on top of a loop that eats CPU cycles. I've seen this mistake a lot—developers treating Fibers like threads, forgetting that PHP is still single-threaded. The Fiber doesn't magically make the network call happen in the background; it only allows you to stop executing that specific block of code.

Shifting to a Scheduler Pattern

The professional way to handle this is to decouple the mechanism (the Fiber) from the policy (the Scheduler). Instead of the main loop blindly resuming everything, the Fiber should suspend itself and "register" its interest in a specific event—like a socket becoming readable—with a central scheduler. The scheduler then uses something like stream_select() to wait for any of the pending requests to finish before resuming the specific Fiber associated with that request.

This is a fundamental shift in thinking. You stop asking "is this Fiber done?" and start asking "which of my resources is ready for action?"

class Scheduler {
    private array $waiting = [];

    public function add(Fiber $fiber, $socket) {
        $this->waiting[(int)$socket] = ['fiber' => $fiber, 'socket' => $socket];
    }

    public function run() {
        while (!empty($this->waiting)) {
            $read = array_column($this->waiting, 'socket');
            $write = $except = null;

            // This is the secret sauce: the OS tells us who is ready
            if (stream_select($read, $write, $except, 0, 200000) > 0) {
                foreach ($read as $socket) {
                    $id = (int)$socket;
                    $fiber = $this->waiting[$id]['fiber'];
                    unset($this->waiting[$id]);
                    $fiber->resume();
                }
            }
        }
    }
}

The Trade-off: Complexity vs. Throughput

Now, you might be wondering why you'd bother with the scheduler when a simple curl_multi_exec does something similar. The trade-off is about composability. When you use a scheduler with Fibers, your business logic remains linear. You write $data = $httpClient->get($url);, and inside that get() method, the Fiber suspends itself. To the developer writing the API logic, the code looks synchronous, but under the hood, the scheduler is juggling a thousand other requests.

The cost is that you can no longer use standard blocking functions. If you call file_get_contents() or a standard PDO query inside a Fiber, you block the entire process, including the scheduler. Everything grinds to a halt. You have to commit to an ecosystem of non-blocking libraries or write your own wrappers around PHP's stream functions. It's a steep architectural commitment, but for high-concurrency tools, it's the only way to truly scale a single PHP process.




📋 Practical Task

Exercise: Building a Non-Blocking Socket Poller

Your task is to implement a basic FiberScheduler class that can manage multiple socket connections without blocking the main execution loop.

Requirements:

  • Create a FiberScheduler class with a method enqueue(Fiber $fiber, $resource).
  • Implement a run() method that uses stream_select() to monitor the registered resources.
  • The scheduler must only resume() a Fiber when its associated socket is actually ready to be read.
  • Write a test script that creates three Fibers, each attempting to read from a different open network socket (you can use fsockopen to connect to a public site like google.com on port 80), and ensure they are resumed in the order they become ready, not necessarily the order they were started.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.