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
159: AMPHP Async Framework Overview
Up until now, everything we've done in PHP has been linear. You call a function, you wait for it to finish, and then you move to the next line. That's fine for most things, but it's a nightmare when you're dealing with I/O-bound tasks—like hitting five different third-party APIs to aggregate data for a single dashboard. If each API takes 200ms, your user is staring at a loading spinner for a full second, even though your CPU is doing almost nothing.
That's where AMPHP comes in. It brings a non-blocking, event-driven architecture to PHP. Instead of waiting for a network response, AMPHP allows the program to "pause" that specific task and work on something else until the response actually arrives.
Fetching multiple APIs without the wait
Let's build a simple "Service Health Checker." We want to check the status of a few different endpoints simultaneously. If we did this the traditional way, we'd loop through the URLs and wait for each one. With AMPHP, we can fire them all off at once.
First, you'll need the HTTP client: composer require amphp/http-client. Here is how I'd start sketching this out:
'https://www.google.com',
'GitHub' => 'https://github.com',
'PHP.net' => 'https://www.php.net',
];
$client = HttpClientBuilder::buildDefault();
$futures = [];
foreach ($urls as $name => $url) {
// We wrap the request in async() to create a "Future"
$futures[$name] = async(fn() => $client->request(new Request($url))->getStatus());
}
// Wait for all of them to resolve
$results = all($futures);
foreach ($results as $name => $status) {
echo "$name returned status $status\n";
}
The "blocking" habit mistake
When I first started with async PHP, I kept falling back into my synchronous habits. I remember trying to add a logging feature to the loop above. I thought, "I'll just quickly write the request time to a local file using file_put_contents()."
I added this inside the async closure:
async(function() use ($client, $url) {
$status = $client->request(new Request($url))->getStatus();
file_put_contents('log.txt', "Checked $url\n", FILE_APPEND); // The mistake!
return $status;
})
The problem? file_put_contents is a blocking function. Even though I'm inside an async block, that specific function tells the entire PHP process: "Stop everything until this file is written to disk." In a small script, you might not notice. In a high-traffic server, you've just killed your concurrency. If you're using AMPHP, you have to commit to the ecosystem. For file I/O, I should have used amphp/file to keep the event loop spinning.
Handling failures gracefully
In the real world, APIs fail. If one of the URLs in my all($futures) call throws an exception, the whole all() call will throw that exception, and I'll lose the results from the APIs that actually worked. That's frustrating.
To fix this, I'll wrap the internal logic in a try-catch block inside the async closure. This way, the "Future" resolves to an error message instead of crashing the whole batch.
$futures[$name] = async(function() use ($client, $url) {
try {
$response = $client->request(new Request($url));
return $response->getStatus();
} catch (\Throwable $e) {
return "Error: " . $e->getMessage();
}
});
Now, all($futures) will always return an array containing either the status code or the error string, regardless of whether the network request succeeded. This pattern—isolating failures within the async closure—is crucial for building resilient concurrent systems.
📋 Practical Task
Build a Concurrent Page-Title Scraper
Your task is to create a script using AMPHP that takes an array of 5 different website URLs and fetches the HTML of each page concurrently. Instead of just checking the status code, you must extract the <title> tag from each page using a regular expression or DOMDocument.
Requirements:
- Use
amphp/http-clientto fetch the pages. - Use
Amp\async()` andAmp\Future\all()` to ensure the requests happen in parallel. - Implement a try-catch block inside each async closure to handle 404s or connection timeouts so that one failing site doesn't stop the others.
- Output the results in a clean list: "Site Name: [Title Text]".
There are no comments for now.