PHP 8.5 and Fibers: Optimize Asynchronous Requests Without a Framework
Learn how to use Fibers in PHP 8.5 to handle asynchronous and parallel I/O operations cleanly, without relying on a heavy framework.
As PHP continues to evolve, asynchronous execution and concurrency have become central topics for developers of high-performance web applications. By introducing and refining Fibers, PHP can suspend and resume blocks of code, making non-blocking I/O easier to manage without the complexity of traditional callback hell.
What PHP Fibers are and why to use them
Fibers are interruptible blocks of code with their own stack. They let developers write asynchronous logic with a fully sequential syntax. This approach provides several benefits:
- No heavy framework: Complex libraries or third-party runtimes are not required to benefit from concurrent execution.
- Clean code: Nested callbacks and complex promises are avoided, preserving the readability of traditional synchronous code.
- Performance and non-blocking I/O: They are useful for parallel HTTP calls, database queries or file-system operations.
Practical example: HTTP calls and parallel I/O
Consider a scenario in which two external APIs or two independent I/O operations must be queried. Instead of running them sequentially and blocking the request, they can be coordinated through Fibers:
<?php
$fiber1 = new Fiber(function(): void {
echo "Inizio recupero dati da API A...\n";
Fiber::suspend('Dati API A in elaborazione');
echo "Completato recupero dati da API A!\n";
});
$fiber2 = new Fiber(function(): void {
echo "Inizio recupero dati da API B...\n";
Fiber::suspend('Dati API B in elaborazione');
echo "Completato recupero dati da API B!\n";
});
// Avvio delle Fiber
$res1 = $fiber1->start();
$res2 = $fiber2->start();
// Ripresa dell'esecuzione
$fiber1->resume();
$fiber2->resume();
?>When to use Fibers instead of the traditional approach
Fibers are ideal when an application must manage several blocking I/O operations. They do not replace multithreading for CPU-intensive tasks, but they handle network and disk waiting times effectively.
Conclusion
Native Fibers are a major step forward for modern PHP development. They make it possible to build fast and efficient microservices, crawlers and API clients while remaining inside the plain PHP ecosystem.
Official sources
Share
What's Your Reaction?
Like
0
Dislike
0
Love
0
Funny
0
Angry
0
Sad
0
Wow
0