Site icon NexGismo

PHP Fibers: The Future of Asynchronous Programming

PHP Fibers

For years, PHP has carried the reputation of being a “synchronous-only” language. Every request runs in a straight line: one task finishes, then the next begins. While this simplicity is why many developers love PHP, it also means PHP has historically struggled with the kind of non-blocking, asynchronous programming that powers modern real-time apps, APIs, and streaming services.

But with PHP Fibers, introduced in PHP 8.1, the story is changing. Fibers give PHP developers a new tool for cooperative multitasking—allowing functions to pause and resume, without introducing parallelism or true asynchronous I/O on their own. They don’t replace traditional async/await found in JavaScript or Python, but they provide a stepping stone—bringing PHP closer to modern, event-driven architectures. If you’re new to PHP 8.1, check out our Introduction to PHP 8 Features article to see what else is new.

In this blog, we’ll explore what PHP Fibers are, how they work, why they matter, and how you can use them in real-world projects.


What Are PHP Fibers?

At its core, a PHP Fiber is a lightweight code block with its own stack and state, which can be started, suspended, and resumed cooperatively by the main program. Think of it as a way to pause and resume a piece of code without losing its execution context.

This “pause and resume” behavior is the essence of Fibers.


Why Do PHP Fibers Matter?

Traditionally, PHP execution is blocking:

This is fine for simple web apps, but in an era of real-time dashboards, microservices, and API-heavy applications, blocking code feels outdated.

PHP Fibers give developers a way to:

References: PHP Manual on Fibers, PHP-Watch Fibers 8.1


How Do Fibers Work in PHP?

Fibers provide functions to start, suspend, resume, throw exceptions, and return values. You can also check their state using isStarted(), isSuspended(), and isTerminated().

Basic Example

$fiber = new Fiber(function (): void {
    $value = Fiber::suspend('Hello from Fiber!');
    echo "Fiber resumed with: $value\n";
});

echo $fiber->start(); // Suspends and outputs: Hello from Fiber!
$fiber->resume('World'); // Resumes and outputs: Fiber resumed with: World

Using FiberError and Fiber Exit

$fiber = new Fiber(function () {
    echo "Running fiber\n";
});

$fiber->start();
try {
    $fiber->resume(); // Throws FiberError because fiber already terminated
} catch (FiberError $e) {
    echo "Caught FiberError: " . $e->getMessage();
}

Real-World Use Cases with PHP Fibers (with Code Examples)

1. Asynchronous HTTP Requests (API Calls in Parallel)

Fibers allow for cooperative multitasking in PHP by enabling functions to pause and resume execution. However, they do not provide asynchronous I/O or concurrency by themselves. For true async behavior, they need to be integrated with an event loop or a framework like ReactPHP or Amp.

function asyncHttpRequest(string $url): Fiber {
    return new Fiber(function () use ($url) {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        curl_close($ch);
        Fiber::suspend($response);
    });
}

$fiber1 = asyncHttpRequest("https://jsonplaceholder.typicode.com/posts/1");
$fiber2 = asyncHttpRequest("https://jsonplaceholder.typicode.com/posts/2");

$response1 = $fiber1->start();
$response2 = $fiber2->start();
$result1 = $fiber1->resume();
$result2 = $fiber2->resume();

Note: This example uses curl_exec(), which is still a blocking operation. While Fibers let you pause execution and return later, they don’t make blocking I/O non-blocking. To perform true async HTTP calls, use a library like Amp or ReactPHP that provides non-blocking network I/O.

2. Non-Blocking File Processing with PHP Fibers

function processFile(string $filename): Fiber {
    return new Fiber(function () use ($filename) {
        $handle = fopen($filename, "r");
        while (!feof($handle)) {
            $line = fgets($handle);
            echo "[$filename] Processing: " . trim($line) . "\n";
            Fiber::suspend();
        }
        fclose($handle);
    });
}

$fiber1 = processFile("log1.txt");
$fiber2 = processFile("log2.txt");
$fiber1->start();
$fiber2->start();
while ($fiber1->isSuspended() || $fiber2->isSuspended()) {
    if ($fiber1->isSuspended()) $fiber1->resume();
    if ($fiber2->isSuspended()) $fiber2->resume();
}

Note: fopen() and fgets() are blocking functions. This example demonstrates the cooperative multitasking behavior of Fibers but does not achieve true non-blocking file I/O. For actual asynchronous file access, you’d need a compatible event-driven library.

3. Cooperative Task Scheduler Using PHP Fibers

class Scheduler {
    private array $queue = [];
    public function add(Fiber $fiber): void {
        $this->queue[] = $fiber;
    }
    public function run(): void {
        while ($this->queue) {
            $fiber = array_shift($this->queue);
            if (!$fiber->isStarted()) {
                $fiber->start();
            } elseif ($fiber->isSuspended()) {
                $fiber->resume();
            }
            if (!$fiber->isTerminated()) {
                $this->queue[] = $fiber;
            }
        }
    }
}

4. Real-Time WebSocket Server with PHP Fibers

use Amp\Socket\Server;
use Revolt\EventLoop;
require 'vendor/autoload.php';

EventLoop::run(function () {
    $server = Server::listen("0.0.0.0:8080");
    while ($socket = $server->accept()) {
        new Fiber(function () use ($socket) {
            $data = $socket->read();
            $socket->write("You said: " . $data);
        })->start();
    }
});

In this example, Fibers are used together with Revolt and Amp—two event-driven libraries that provide true async I/O in PHP. Fibers here help manage multiple socket connections in a clean, sequential style while the underlying event loop handles I/O asynchronously.

Pros and Cons of Using PHP Fibers

Pros:

Cons:


Best Practices for Fibers

  1. Combine Fibers with async libraries like ReactPHP or Amp for actual non-blocking behavior
  2. Keep Fiber logic lightweight and isolated
  3. Don’t expect Fibers to improve performance alone—they are control flow tools, not performance optimizers
  4. Handle FiberError and unexpected terminations with care
  5. Avoid using Fibers for CPU-bound tasks or parallelism—consider other approaches like parallel or multi-process execution

PHP Fibers vs. JavaScript Async/Await

FeaturePHP FibersJavaScript Async/Await
Execution ModelCooperative (manual yielding)Event Loop + Promises
SyntaxManual via Fiber APIBuilt-in async/await keywords
EcosystemEmerging (ReactPHP, Amp)Mature and widely adopted
Async I/O SupportVia third-party libsNative with fetch, etc.
Learning CurveMedium (manual control flow)Low (syntax sugar over promises)

Conclusion

PHP Fibers mark a significant milestone for PHP, enabling non-blocking, efficient, and modern applications. Combined with frameworks like ReactPHP Guide and AMPHP Concurrency, PHP Fibers open doors to real-time apps and cleaner async code. Explore more in our PHP tutorials.


References



Exit mobile version