Web Development
30-05-2024

Fibers in PHP

Dmytro Tus
Full Stack Web developer

Fibers is a new feature which introduced in php 8.1

Example of code

 

<?php

function asyncReadFile($filePath) {
    return new Fiber(function() use ($filePath) {
        echo('starting to get content' . PHP_EOL);
        $content = "Content of $filePath";
        
        // Pause fiber and return the result
        Fiber::suspend($content);
    });
}

function processMyFilesAsync() {
    $file1 = 'file1.txt';
    $file2 = 'file2.txt';
    
    // Create Fiber for getting files
    $fiber1 = asyncReadFile($file1);
    $fiber2 = asyncReadFile($file2);
    
    // Run 2 fibers at the same time
    $content1 = $fiber1->start();
    $content2 = $fiber2->start();
    
    // Show results
    echo "Read: $content1\n";
    echo "Read: $content2\n";
    
    // Resume processing fibers ( if needed )
    $fiber1->resume();
    $fiber2->resume();
}

processMyFilesAsync();

echo('finish');

/// output
starting to get content
starting to get content
Read: Content of file1.txt
Read: Content of file2.txt
finish

Where it can be used.

At this moment I have seen only one place where it was implemented. 

It is ReactPHP library with async/await functinality. Like in JavaScript.

https://reactphp.org/async/

 


Tags:

Another posts