02: Elapsed Time with Time\Duration
Overview
Section titled “Overview”Build a retry-delay calculator using seconds and milliseconds. A duration measures an amount of elapsed time and carries no calendar date or time zone.
Prerequisites
Section titled “Prerequisites”- PHP 8.6 CLI. Confirm the version with
php --version. - Review the previous chapter if you’re following the series in order.
Allow about 10 minutes for the walkthrough and exercise.
What You’ll Build
Section titled “What You’ll Build”A runnable duration.php example.
Step 1: Run the example (~5 min)
Section titled “Step 1: Run the example (~5 min)”Run the following from the root of the Code with PHP repository.
php code/php-8-6/02-duration/duration.php<?php
declare(strict_types=1);
use Time\Duration;
$baseDelay = Duration::fromMilliseconds(750);$attemptDelay = $baseDelay->multiplyBy(3);$delay = min($attemptDelay, Duration::fromSeconds(2));
printf("Base: %d s %d ns\n", $baseDelay->seconds, $baseDelay->nanoseconds);printf("Capped delay: %d s %d ns\n", $delay->seconds, $delay->nanoseconds);Expected Result
Section titled “Expected Result”Base: 0 s 750000000 nsCapped delay: 2 s 0 nsWhy It Works
Section titled “Why It Works”Factories make the unit explicit. Arithmetic produces a new duration, so a shared base delay remains intact. The seconds and nanoseconds properties expose normalized components, and durations can be compared directly.
Exercise
Section titled “Exercise”Calculate the delay for attempts zero through four with a cap of two seconds. Check that the final delay stays at the cap.
Wrap-up
Section titled “Wrap-up”Continue with Wait for I/O with Io\Poll.