×

php · level 3 · unit 6 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Hand a class its tools instead of letting it build its own.

A sign-up class needs a mailer to send welcome emails. That mailer is a . If the class writes new SmtpMailer() inside itself, it is welded to real email forever, and every test sends a real message to a real person.

flips it round. The class asks for a Mailer in its constructor, and whoever builds it hands one in. Because Mailer is an interface, any class keeping the promise fits. In a test, hand in a that writes to the screen instead.

<?php
interface Mailer {
    public function send(string $to, string $text): void;
}
class ScreenMailer implements Mailer {
    public function send(string $to, string $text): void { echo "To $to: $text\n"; }
}
class SignUp {
    public function __construct(private Mailer $mailer) {}

    public function register(string $email): void {
        $this->mailer->send($email, "Welcome aboard!");
    }
}
$signUp = new SignUp(new ScreenMailer());
$signUp->register("leo@example.com");

Wrap new in brackets, as in (new SignUp($mailer))->register(...), to call a method on the new object straight away.