bhylu.com

Advertisements

PHP Interfaces

An interface states operations a caller can rely on. A small injected implementation lets tests avoid contacting a real external system.

How it works

Define a capability such as sending a receipt, then supply a collaborator to the operation that needs it. The caller should not construct a production mail connection internally just to finish a calculation. This example uses a collecting implementation whose output can be inspected. An interface does not define delivery guarantees, retries or privacy policy automatically; those remain part of the service contract.

Run it locally

Run this complete source locally with PHP 8.2 or newer. Save it using the filename shown and run the command below. PHP is not currently available in Bhylu’s browser playground. Apache and MySQL are not needed for an ordinary CLI example.

php -l interfaces.php
php interfaces.php

Download this source as a local PHP lab file. Keep lab files separate from the Bhylu project and production data.

Example

PHP 8.2+ · interfaces.php

<?php
declare(strict_types=1);

interface ReceiptSink { public function send(string $message): void; }
class MemorySink implements ReceiptSink {
    public array $messages = [];
    public function send(string $message): void { $this->messages[] = $message; }
}
function issueReceipt(ReceiptSink $sink, int $id): void { $sink->send("Loan $id recorded"); }
$sink = new MemorySink();
issueReceipt($sink, 27);
echo $sink->messages[0], "\n";

Expected result

Loan 27 recorded

The operation knows only the interface. The memory implementation records exactly one message without sending email, which makes a focused test possible. A production adapter could implement the same call shape, but its failure and retry policy must be documented rather than inferred from this teaching fixture.

Check the official PHP manual for detailed version and API contracts.