PHP 8.1 introduced the new Fiber class (see the proposed RFC here https://wiki.php.net/rfc/fiber), which allows running coroutines inside your script, i.e. two functions executing simultaneously.
Fibers support three methods:
start()suspend()resume()
Let’s see how to use them by using some examples. These examples are implemented as PHPUnit tests which made simple assertions.
Fiber is not executed until it is started
In order to run the code inside the fiber closure, the start() method must be called from a fiber instance.
1/** @test */
2public function fiber_is_not_executed_until_it_is_started()
3{
4 $value = false;
5
6 $fiber = new \Fiber(function() use (&$value) {
7 $value = true;
8 });
9
10 $this->assertEquals(false, $value);
11
12 $fiber->start();
13
14 $this->assertEquals(true, $value);
15}
Fiber can be resumed
A suspended fiber can be resumed at any time by calling the resume() method on the fiber instance.
1/** @test */
2public function fiber_can_be_resumed()
3{
4 $value = false;
5
6 $fiber = new \Fiber(function() use (&$value) {
7 \Fiber::suspend();
8 $value = true;
9 });
10
11 $fiber->start();
12 $fiber->resume();
13
14 $this->assertEquals(true, $value);
15}
Fiber can pass values when suspended
When the suspend() method is called, an additional parameter can be passed and it is used as a return value for the start() method that previously started the fiber.
1/** @test */
2public function fiber_can_pass_values_when_suspended()
3{
4 $fiber = new \Fiber(function() {
5 \Fiber::suspend('suspended');
6 });
7
8 $state = $fiber->start();
9
10 $this->assertEquals('suspended', $state);
11}
Fiber can receive value when resumed
When the resume() method is called, an additional parameter can be passed and it is used as a return value for the suspend() method that previously suspended the fiber.
1/** @test */
2public function fiber_can_receive_value_when_resumed()
3{
4 $fiber = new \Fiber(function() {
5 $value = \Fiber::suspend();
6 $this->assertEquals('resumed', $value);
7 });
8
9 $fiber->start();
10 $fiber->resume('resumed');
11}
This is the core of fibers usage. If you have comments or suggestions, please leave a comment or contact me!