PHP
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions
-
Section 4: Object-Oriented PHP
-
Section 5: Working with Data
-
Section 6: Modern PHP (PHP 8)
-
Section 7: Working with Files and Networking
-
Section 8: Common PHP Frameworks Overview
-
Section 9: Tooling and Ecosystem
-
Section 10: Practical Projects
-
Section 11: Interview Practice
-
Section 12: More Standard Library
-
Section 13: Data Structures and Algorithms in PHP
-
Section 14: More Practice Exercises
-
Section 15: More Security and Best Practices
-
Section 16: More Testing and Tooling
-
Section 17: WordPress-Style CMS Concepts
-
Section 18: Advanced OOP Practice
-
Section 19: More Web Fundamentals
-
Section 20: Database Practice
-
Section 21: PHP Manual: Array Functions
-
Section 22: PHP Manual: Date and Calendar Functions
-
Section 23: PHP Manual: Filesystem and Directory Functions
-
Section 24: PHP Manual: Filter and Var Handling
-
Section 25: PHP Manual: Math Functions
-
Section 26: PHP Manual: JSON and XML
-
Section 27: PHP Manual: Network and Stream Functions
-
Section 28: PHP Manual: Error and Exception Handling
-
Section 29: PHP Manual: Output Control and Misc
-
Section 30: PHP Manual: FTP, Zip, and Mail
-
Section 31: Modern PHP Frameworks Deep Dive
-
Section 32: PHP Design Patterns
-
Section 33: More Practice Exercises
-
Section 34: PHP Performance and Deployment
-
Section 35: More Interview Practice
-
Section 36: More PHP Standard Library
-
Section 37: PHP Concurrency and Async
-
Section 38: More Web Development Practice
-
Section 39: PHP Testing Deep Dive
-
Section 40: Composer and Package Development
-
Section 41: PHP Security Deep Dive
-
Section 42: More Practical Projects
-
Section 43: Legacy PHP Maintenance
-
Section 44: More Algorithm Practice
-
Section 45: Final Practice and Review
-
Section 46: PHP for E-Commerce Patterns
-
Section 47: PHP API Design Deep Dive
-
Section 48: PHP Caching Strategies
-
Section 49: PHP Queue and Background Jobs
-
Section 50: PHP Multi-Tenancy Patterns
-
Section 51: PHP Real-Time Features
-
Section 52: PHP CMS and Content Modeling
-
Section 53: PHP Internationalization
-
Section 54: More Framework-Specific Practice
-
Section 55: PHP Legacy Code Refactoring
-
Section 56: More Practice Projects Round 2
-
Section 57: PHP Command-Line Applications
-
Section 58: PHP and Microservices
-
Section 59: More Interview and Review Round 2
156: Fibers Revisited In Depth
By now, you know that Fibers give us the ability to pause a block of code and jump back to the main execution flow. On the surface, it feels like magic. But if you're like I was when I first encountered them, your first instinct is probably to use them as a way to "multitask" manually. You create a Fiber, you suspend it when you hit a slow I/O call, and you resume it when you think it's ready. It works for a tiny script, but it's a recipe for disaster in a real application.
The Manual Orchestration Trap
The naive way to use Fibers is to treat them as individual units of work that you manage by hand. Imagine you're building a dashboard that needs to fetch data from three different third-party APIs. You might be tempted to wrap each API call in a Fiber, suspend the Fiber while the network request is pending, and then manually call $fiber->resume() in a while loop.
// The "Manual" way - don't actually do this in production
$fibers = [];
$fibers[] = new Fiber(fn() => fetchApi('https://api.a.com'));
$fibers[] = new Fiber(fn() => fetchApi('https://api.b.com'));
foreach ($fibers as $f) $f->start();
while (count($fibers) > 0) {
foreach ($fibers as $key => $f) {
if ($f->isTerminated()) {
unset($fibers[$key]);
continue;
}
// We're just guessing or blindly resuming
$f->resume();
}
usleep(1000);
}
The problem here is that you've just built a very inefficient "busy-wait" loop. You're resuming Fibers regardless of whether the data they are waiting for has actually arrived. You aren't actually gaining the benefits of non-blocking I/O; you're just adding the overhead of Fiber context switching on top of a loop that eats CPU cycles. I've seen this mistake a lot—developers treating Fibers like threads, forgetting that PHP is still single-threaded. The Fiber doesn't magically make the network call happen in the background; it only allows you to stop executing that specific block of code.
Shifting to a Scheduler Pattern
The professional way to handle this is to decouple the mechanism (the Fiber) from the policy (the Scheduler). Instead of the main loop blindly resuming everything, the Fiber should suspend itself and "register" its interest in a specific event—like a socket becoming readable—with a central scheduler. The scheduler then uses something like stream_select() to wait for any of the pending requests to finish before resuming the specific Fiber associated with that request.
This is a fundamental shift in thinking. You stop asking "is this Fiber done?" and start asking "which of my resources is ready for action?"
class Scheduler {
private array $waiting = [];
public function add(Fiber $fiber, $socket) {
$this->waiting[(int)$socket] = ['fiber' => $fiber, 'socket' => $socket];
}
public function run() {
while (!empty($this->waiting)) {
$read = array_column($this->waiting, 'socket');
$write = $except = null;
// This is the secret sauce: the OS tells us who is ready
if (stream_select($read, $write, $except, 0, 200000) > 0) {
foreach ($read as $socket) {
$id = (int)$socket;
$fiber = $this->waiting[$id]['fiber'];
unset($this->waiting[$id]);
$fiber->resume();
}
}
}
}
}
The Trade-off: Complexity vs. Throughput
Now, you might be wondering why you'd bother with the scheduler when a simple curl_multi_exec does something similar. The trade-off is about composability. When you use a scheduler with Fibers, your business logic remains linear. You write $data = $httpClient->get($url);, and inside that get() method, the Fiber suspends itself. To the developer writing the API logic, the code looks synchronous, but under the hood, the scheduler is juggling a thousand other requests.
The cost is that you can no longer use standard blocking functions. If you call file_get_contents() or a standard PDO query inside a Fiber, you block the entire process, including the scheduler. Everything grinds to a halt. You have to commit to an ecosystem of non-blocking libraries or write your own wrappers around PHP's stream functions. It's a steep architectural commitment, but for high-concurrency tools, it's the only way to truly scale a single PHP process.
📋 Practical Task
Exercise: Building a Non-Blocking Socket Poller
Your task is to implement a basic FiberScheduler class that can manage multiple socket connections without blocking the main execution loop.
Requirements:
- Create a
FiberSchedulerclass with a methodenqueue(Fiber $fiber, $resource). - Implement a
run()method that usesstream_select()to monitor the registered resources. - The scheduler must only
resume()a Fiber when its associated socket is actually ready to be read. - Write a test script that creates three Fibers, each attempting to read from a different open network socket (you can use
fsockopento connect to a public site like google.com on port 80), and ensure they are resumed in the order they become ready, not necessarily the order they were started.
There are no comments for now.