Skip to Content
Course content

159: AMPHP Async Framework Overview

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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-client to fetch the pages.
  • Use Amp\async()` and Amp\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]".
Rating
0 0

There are no comments for now.

to be the first to leave a comment.