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
33: Fibers for Lightweight Concurrency
I've talked to plenty of developers who see "Fibers" in the PHP 8.1+ documentation and immediately think, "Great, I can finally do true multithreading in PHP." They assume that by wrapping code in a Fiber, the CPU will suddenly start splitting tasks across multiple cores, allowing two heavy loops to run at the exact same time.
The "Parallelism" Myth vs. Cooperative Multitasking
Here is the hard truth: Fibers do not provide parallelism. If you start two Fibers and each one contains a while loop that calculates prime numbers for ten seconds, your script will still take twenty seconds to finish. PHP is still single-threaded.
// This will NOT run in parallel
$fiber1 = new Fiber(function() {
for ($i = 0; $i < 1000000000; $i++) {}
echo "Fiber 1 done\n";
});
$fiber2 = new Fiber(function() {
for ($i = 0; $i < 1000000000; $i++) {}
echo "Fiber 2 done\n";
});
$fiber1->start();
$fiber2->start();
// You'll wait for 1 to finish entirely before 2 even starts.
So, what are they actually for? Fibers are about cooperative concurrency. Instead of the operating system forcing a thread to stop (preemptive multitasking), the code itself decides when to "pause" and hand control back to the main program. It's less about doing two things at once and more about not sitting around doing nothing while you wait for a slow network response or a file read.
Stopping the Clock with Suspend and Resume
The real power of a Fiber is the ability to pause its entire execution state—including the call stack and local variables—and jump back to where you were later. I like to think of it as a "bookmark" for your code.
Imagine you're building a system that fetches data from three different APIs. Normally, you'd wait for API A, then B, then C. With Fibers, you can start the request for A, Fiber::suspend() it to let the program do other work, and then resume() it once the socket actually has data ready to read.
$fiber = new Fiber(function(): void {
echo "Starting API request...\n";
// We simulate a non-blocking I/O wait here
Fiber::suspend('waiting_for_network');
echo "Processing API response!\n";
});
$value = $fiber->start();
echo "The fiber said: " . $value . "\n"; // Output: waiting_for_network
// ... Imagine we do other work here, like logging or handling other requests ...
echo "Now we resume.\n";
$fiber->resume();
In the example above, the Fiber didn't finish. It stopped mid-function, remembered exactly where it was, and gave control back to the main script. When we called resume(), it didn't start over from the top; it woke up exactly where Fiber::suspend() was called.
Orchestrating Work with a Simple Scheduler
On their own, Fibers are just low-level primitives. You rarely use them raw in a production app; instead, you use a library like Amp or ReactPHP. But to understand how those libraries work, you need to understand the "Scheduler" pattern. A scheduler is just a loop that keeps track of all active Fibers and resumes them when they are ready to move forward.
I've found that the best way to wrap your head around this is to imagine a "Task Manager" that polls different jobs. If a job is suspended, the manager moves to the next one. This prevents one slow I/O operation from freezing your entire server process.
$tasks = [
new Fiber(fn() => print("Task A started\n" . Fiber::suspend() . " Task A finished\n")),
new Fiber(fn() => print("Task B started\n" . Fiber::suspend() . " Task B finished\n")),
];
// Start them all
foreach ($tasks as $task) {
$task->start();
}
// In a real app, we'd check if the socket is readable here.
// For this demo, we just resume them manually.
foreach ($tasks as $task) {
$task->resume(" [Data Received] ");
}
Notice how the output is interleaved? "Task A started", "Task B started", and then the finishes. We've effectively managed multiple execution contexts without ever needing multiple CPU threads.
📋 Practical Task
Build a Cooperative Mock-API Aggregator
Your goal is to simulate a scenario where you are fetching data from three different "slow" sources without blocking the entire script execution linearly. Since we don't have a real asynchronous event loop here, you will simulate the "ready" state of the APIs.
Requirements:
- Create three separate
Fiberinstances. Each should represent a request to a different service (e.g., "User Service", "Order Service", "Payment Service"). - Inside each Fiber, print a message saying the request has started, then call
Fiber::suspend(), passing a string identifying which service is waiting. - After the suspension, the Fiber should print a message saying the data has been "received" and return a mock data array.
- Implement a
whileloop in your main script that keeps track of these Fibers. The loop should continue as long as there are Fibers that have not yet terminated (use$fiber->isTerminated()). - Inside the loop, iterate through your list of Fibers and
resume()them.
Expected Behavior: Your console should show all three services "starting" before any of them "finish," demonstrating that the execution is jumping between contexts rather than finishing one service entirely before moving to the next.
There are no comments for now.