### Install amphp/amp with Composer Source: https://github.com/amphp/amp/blob/3.x/README.md Installs the core `amphp/amp` library as a Composer dependency, providing fundamental primitives for asynchronous PHP programming. ```bash composer require amphp/amp ``` -------------------------------- ### Install Revolt Event Loop with Composer Source: https://github.com/amphp/amp/blob/3.x/README.md Installs the `revolt/event-loop` library as a Composer dependency, which is essential for scheduling events and managing the event loop in AMPHP applications. ```bash composer require revolt/event-loop ``` -------------------------------- ### Asynchronous Value Production using Amp\DeferredFuture Source: https://github.com/amphp/amp/blob/3.x/README.md This PHP example illustrates how to create an asynchronous value producer function (`asyncMultiply`) using `Amp\DeferredFuture`. It shows how to return a `Future` immediately and then complete it with a computed value after a delay using `Revolt\EventLoop::delay`, demonstrating a common pattern for deferred results. ```php complete($x * $y); }); return $deferred->getFuture(); } $future = asyncMultiply(6, 7); $result = $future->await(); var_dump($result); // int(42) ``` -------------------------------- ### PHP Asynchronous Coroutine with Amp\async() Source: https://github.com/amphp/amp/blob/3.x/README.md Illustrates starting an independent coroutine (fiber) using `Amp\async()` and `Amp\delay()` to manage asynchronous execution flow. This example shows how `Amp\async()` allows for concurrent execution of code blocks without blocking the main script flow, with `Amp\delay()` simulating an asynchronous operation. ```php "https://www.google.com", "news" => "https://news.google.com", "bing" => "https://www.bing.com", "yahoo" => "https://www.yahoo.com", ]; try { $responses = Future\await(array_map(function ($uri) use ($httpClient) { return Amp\async(fn () => $httpClient->request(new Request($uri, 'HEAD'))); }, $uris)); foreach ($responses as $key => $response) { printf( "%s | HTTP/%s %d %s\n", $key, $response->getProtocolVersion(), $response->getStatus(), $response->getReason() ); } } catch (Exception $e) { // If any one of the requests fails the combo will fail echo $e->getMessage(), "\n"; } ``` -------------------------------- ### PHP Asynchronous Operation with Callback Pattern Source: https://github.com/amphp/amp/blob/3.x/README.md Shows a traditional callback-based approach for handling asynchronous operations. This pattern involves passing a function that gets invoked upon completion, often leading to nested callbacks ('callback hell') and making error handling cumbersome, highlighting its limitations compared to Futures. ```php doSomething(function ($error, $value) { if ($error) { /* ... */ } else { /* ... */ } }); ``` -------------------------------- ### Amp\Future Class API Documentation Source: https://github.com/amphp/amp/blob/3.x/README.md Detailed API documentation for the `Amp\Future` class, outlining its core methods for managing asynchronous operation results. It includes `await()` for blocking until completion, `map()` for transforming successful results, `catch()` for handling errors, and `finally()` for executing code regardless of outcome. ```APIDOC Amp\Future: await(): mixed Description: Suspends the current coroutine until the future is completed or errors. The future result is returned or an exception thrown if the future errored. map(Closure $map): Future Description: Attaches a callback which is invoked if the future completes successfully, passing the future result as an argument. Another future is returned, which either completes with the return value of the callback, or errors if the callback throws an exception. Parameters: $map: Closure(mixed $value): mixed - The callback to execute on successful completion. catch(Closure $catch): Future Description: Attaches a callback which is invoked if the future errors, passing the exception as the callback parameter. Another future is returned, which either completes with the return value of the callback, or errors if the callback throws an exception. Parameters: $catch: Closure(Throwable $exception): mixed - The callback to execute on error. finally(Closure $finally): Future Description: Attaches a callback which is always invoked, whether the future completes or errors. Another future is returned, which either completes with same value as the future, or errors if the callback throws an exception. Parameters: $finally: Closure(): void - The callback to execute regardless of completion or error. ``` -------------------------------- ### Amp\DeferredFuture Class API Reference Source: https://github.com/amphp/amp/blob/3.x/README.md API documentation for the `Amp\DeferredFuture` class, which provides methods to manually complete or error a `Future` instance. This advanced API is used for scenarios where a `Future` needs to be returned immediately but its result will be available later. ```APIDOC final class DeferredFuture { public function getFuture(): Future public function complete(mixed $value = null): void public function error(Throwable $throwable): void } ``` -------------------------------- ### PHP Coroutine Suspension with EventLoop Source: https://github.com/amphp/amp/blob/3.x/README.md Demonstrates low-level coroutine suspension and resumption using Revolt's EventLoop and Suspension API. It shows how execution is temporarily interrupted by `suspend()` and resumed by `resume()` from an event loop callback, illustrating the non-blocking nature of coroutines. ```php resume(null); }); print '++ Suspending to event loop...' . PHP_EOL; $suspension->suspend(); print '++ Script end' . PHP_EOL; ``` -------------------------------- ### Amp Utility: now Function Source: https://github.com/amphp/amp/blob/3.x/README.md Documents the `now` utility function. It returns a high-resolution timestamp relative to an arbitrary point in time, suitable for calculating precise time differences in asynchronous operations. ```PHP function now(): float ``` -------------------------------- ### Amp DeferredCancellation for Manual Control Source: https://github.com/amphp/amp/blob/3.x/README.md Illustrates the use of `Amp\DeferredCancellation` for manual cancellation. It involves creating a `DeferredCancellation` instance, registering a custom callback to trigger cancellation, and then passing its associated `Cancellation` object to the operation. This provides fine-grained control over when an operation is cancelled. ```PHP $deferredCancellation = new Amp\DeferredCancellation(); // Register some custom callback somewhere onSomeEvent(fn () => $deferredCancellation->cancel()); request("...", $deferredCancellation->getCancellation()); ``` -------------------------------- ### PHP Awaiting a Future Result with try-catch Source: https://github.com/amphp/amp/blob/3.x/README.md Demonstrates how to await the result of an asynchronous operation represented by a `Future` using `Future::await()`. This method suspends the current coroutine until the Future completes, allowing the result to be directly assigned or an exception caught, simplifying asynchronous code flow. ```php try { $value = doSomething()->await(); } catch (...) { /* ... */ } ``` -------------------------------- ### Amp NullCancellation for Optional Cancellation Source: https://github.com/amphp/amp/blob/3.x/README.md Explains how `NullCancellation` can be used as a placeholder when cancellation is optional, avoiding explicit `if ($cancellation)` checks. It ensures that operations always receive a valid `Cancellation` object, even if it never triggers. ```PHP $cancellation ??= new NullCancellationToken(); ``` -------------------------------- ### PHP Interval Class Usage for Repeating Timers Source: https://github.com/amphp/amp/blob/3.x/README.md The `Interval` class in `amphp/amp` allows registering a callback to be invoked repeatedly within a new coroutine at a specified interval. The timer can be disabled and re-enabled. It's designed to be held by another object, with automatic cancellation upon destruction. Using `weakClosure()` is recommended to prevent circular references and ensure proper garbage collection. ```php // Creates a callback which is invoked every 0.5s // unless disabled or the object is destroyed. $interval = new Interval(0.5, function (): void { // ... }); // Disable the repeating timer, stopping future // invocations until enabled again. $interval->disable(); // Enable the repeating timer. The callback will // not be invoked until the given timeout has elapsed. $interval->enable(); ``` -------------------------------- ### Amp SignalCancellation for Process Signals Source: https://github.com/amphp/amp/blob/3.x/README.md Shows how to use `Amp\SignalCancellation` to cancel an operation when a specific system signal (e.g., `SIGINT`) is received by the process. This allows for graceful shutdown or interruption of long-running tasks. ```PHP request("...", new Amp\SignalCancellation(SIGINT)); ``` -------------------------------- ### Amp Utility: weakClosure Function Source: https://github.com/amphp/amp/blob/3.x/README.md Documents the `weakClosure` utility function. This function wraps a given closure, creating a new closure that maintains a weak reference to any `$this` object it holds. This prevents circular references that could hinder garbage collection, especially useful in event-driven or callback-heavy architectures. ```PHP /** * @template TClosure of \Closure * @param TClosure $closure * @return TClosure */ function weakClosure(Closure $closure): Closure ``` -------------------------------- ### Amp TimeoutCancellation Usage Source: https://github.com/amphp/amp/blob/3.x/README.md Demonstrates how to use `Amp\TimeoutCancellation` to automatically cancel an operation after a specified duration. This is useful for setting time limits on asynchronous tasks. ```PHP request("...", new Amp\TimeoutCancellation(30)); ``` -------------------------------- ### Amp Utility: delay Function Source: https://github.com/amphp/amp/blob/3.x/README.md Documents the `delay` utility function. It suspends the current coroutine for a specified timeout or until a provided cancellation is triggered. It also supports unreferencing the underlying event-loop callback. ```PHP function delay( float $timeout, bool $reference = true, ?Cancellation $cancellation = null, ): void ``` -------------------------------- ### Amp Utility: trapSignal Function Source: https://github.com/amphp/amp/blob/3.x/README.md Documents the `trapSignal` utility function. This function suspends the current coroutine until one of the specified system signals is received or a cancellation is triggered. It returns the signal number that was received and supports unreferencing the event-loop callback. ```PHP /** @param int|array $signals */ function trapSignal( int|array $signals, bool $reference = true, ?Cancellation $cancellation = null, ): int ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.