Lab 01: Fibers & Async

Time: 40 minutes | Level: Advanced | Docker: docker run -it --rm php:8.3-cli bash

Fibers introduce first-class coroutine support in PHP 8.1. Unlike threads, Fibers cooperatively yield control — enabling async-style patterns without extensions.


Step 1: Your First Fiber

A Fiber wraps a callable. Control only switches when explicitly suspended or resumed.

<?php
$fiber = new Fiber(function(): string {
    echo "Fiber: starting\n";
    $value = Fiber::suspend('paused here');
    echo "Fiber: resumed with '$value'\n";
    return 'done';
});

$suspended = $fiber->start();       // Run until first suspend
echo "Main: fiber suspended with '$suspended'\n";
$fiber->resume('hello');            // Resume with a value
echo "Main: fiber returned: " . $fiber->getReturn() . "\n";

📸 Verified Output:

Fiber: starting
Main: fiber suspended with 'paused here'
Fiber: resumed with 'hello'
Main: fiber returned: done

💡 Fiber::suspend() is a static method called inside the fiber. $fiber->resume() is called outside.


Step 2: Fiber Lifecycle States

📸 Verified Output:

💡 A Fiber can only be in one state at a time: Not Started → Running → Suspended ⇄ Running → Terminated.


Step 3: Passing Values In and Out

📸 Verified Output:


Step 4: Fiber Exception Handling

📸 Verified Output:

💡 $fiber->throw(Throwable) injects an exception at the suspension point inside the fiber.


Step 5: Simple Cooperative Scheduler

📸 Verified Output:


Step 6: Coroutine Pipeline Pattern

Chain fibers as processing stages:

📸 Verified Output:


Step 7: Simulated Async I/O

📸 Verified Output:

💡 This pattern forms the basis of real async PHP frameworks like ReactPHP and Amp v3.


Step 8: Capstone — Task Runner with Priorities

Build a priority-aware cooperative task runner:

📸 Verified Output:


Summary

Concept
Method/Feature
Notes

Create Fiber

new Fiber(callable)

Wraps any callable

Start execution

$fiber->start(...$args)

Returns first suspended value

Suspend from inside

Fiber::suspend($value)

Static method inside fiber

Resume from outside

$fiber->resume($value)

Returns next suspended value

Inject exception

$fiber->throw(Throwable)

Throws at suspension point

Get return value

$fiber->getReturn()

Only after termination

Check state

isStarted/isSuspended/isRunning/isTerminated

Mutually exclusive states

Use case

Cooperative multitasking

Schedulers, async I/O simulation

Last updated