Lab 09: Async — amphp

Time: 60 minutes | Level: Architect | Docker: docker run -it --rm php:8.3-cli bash

Overview

Amp v3 is a PHP async framework built on Fibers. It provides Future, async(), delay(), structured concurrency, and cancellation. This lab covers the Amp event loop, parallel task execution, async HTTP, and cancellable operations.


Step 1: Setup

# Inside Docker container
apt-get update -qq && apt-get install -y -q curl unzip
curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer

mkdir /tmp/amplab && cd /tmp/amplab
composer require amphp/amp:^3.0
<?php
require 'vendor/autoload.php';

use Amp\Future;
use function Amp\async;
use function Amp\delay;

echo "Amp version: " . \Composer\InstalledVersions::getVersion('amphp/amp') . "\n";

Step 2: Basic async() and Future

📸 Verified Output:

💡 With delay(0.02) per task sequentially = 100ms. Concurrently = ~20ms. That's the power of async!


Step 3: Future Combinators


Step 4: Coroutines with Fiber


Step 5: Async Simulation — Parallel Tasks

📸 Verified Output:


Step 6: Cancellation


Step 7: amphp/http-client — Async HTTP

💡 Install amphp/http-client separately. The above requires internet access in the Docker container. For offline demos, use simulateApiCall() with delay().


Step 8: Capstone — Async Job Runner

📸 Verified Output:


Summary

Feature
Amp v3 API
Notes

Create async task

async(callable)

Returns Future<T>

Await one

$future->await()

Suspends current fiber

Await all

Future::await([...])

All succeed or throws

First to complete

Future::awaitFirst([...])

Returns [$value, $key]

First success

Future::awaitAny([...])

Ignores exceptions

Delay (non-blocking)

delay(float $seconds)

Timer without blocking process

Cancellation

DeferredCancellation

Cancel any Future

Error handling

try/catch on ->await()

Normal PHP exceptions

Concurrency

Chunk futures

Limit parallel tasks

HTTP client

amphp/http-client

Concurrent HTTP requests

Last updated