Repository and observer

Two interfaces keep a PHP application from knowing too much: one hides where data lives, the other hides who reacts to an event. The examples below are contracts first and working classes second, and every printed line came from a run.

Repository

A repository pretends storage is a simple collection: find by id, save a record. Business code talks to the interface while files or databases hide behind it, so swapping storage never rewrites rules.

<?php interface UserRepo { public function find(int $id): array; public function save(array $user): void; }

The interface is the contract, not a program: it declares two methods and cannot be instantiated. The fake class in the last section fills it, and that example runs.

Observers

Observers react to news without the core flow knowing them: send mail, clear cache, log stats. Registration code announces an event and moves on while each listener handles its own side effect.

<?php interface UserListener { public function onRegistered(array $user): void; } class MailListener implements UserListener { public function onRegistered(array $user): void { echo "mail to " . $user["email"] . "\n"; } } $listener = new MailListener(); $listener->onRegistered(["email" => "ada@example.com"]);

php observer.php

mail to ada@example.com

The listener knows how to mail and nothing about registration, which is why it can be added or removed without a change in the code that registers users.

Simple dispatcher

A tiny dispatcher maps event names to callables and calls each one with the payload. Twenty lines remove the need for tangled includes and let features plug in from any module.

<?php class Events { private array $listeners = []; public function on(string $name, callable $fn): void { $this->listeners[$name][] = $fn; } public function emit(string $name, array $data): void { foreach ($this->listeners[$name] ?? [] as $fn) { $fn($data); } } } $events = new Events(); $events->on("registered", function (array $data): void { echo "handled " . $data["email"], PHP_EOL; }); $events->emit("registered", ["email" => "ada@example.com"]);

php events.php

handled ada@example.com

The name is the only thing the two sides share, and the empty default of ?? [] keeps an event with no listeners quiet.

Test with fakes

Interfaces make tests cheap: a fake repository keeps records in memory and records every save. Business logic runs against the fake in milliseconds with zero database setup.

<?php interface UserRepo { public function find(int $id): array; public function save(array $user): void; } class FakeRepo implements UserRepo { public array $saved = []; public function find(int $id): array { return ["id" => $id]; } public function save(array $user): void { $this->saved[] = $user; } } $repo = new FakeRepo(); $repo->save(["id" => 1, "name" => "Ada"]); echo count($repo->saved), PHP_EOL; echo $repo->find(1)["id"], PHP_EOL;

php fake.php

1
1

The save was recorded in the array and the find answered without a database, which is the whole reason the business code depends on the interface and not on PDO.

Exercises

  1. Add a count() method to UserRepo and implement it in the fake.
  2. Register a second listener for the same event and read both output lines.
  3. Give the dispatcher a once() method that removes a listener after its first call.
  4. Swap the fake for an implementation that writes to a file and run the same checks.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does a repository hide from the business code?

    Answer

    Where and how the data is stored

    The code talks to find() and save(), so a file store and a database are interchangeable behind the interface.

  2. What does an observer keep out of the core flow?

    Answer

    The side effect that follows an event

    Registration announces the event and moves on, while each listener owns its own reaction.

  3. What does the small dispatcher map an event name to?

    Answer

    A list of callables

    Each on() call appends a callable, and emit() calls every one of them with the payload.

  4. Why does a fake repository make a test fast?

    Answer

    It stores records in memory and needs no database

    The whole test runs in one process, without a server, a schema or a network round trip.

  5. What does this program print? <?php interface UserRepo { public function find(int $id): array; } class FakeRepo implements UserRepo { public function find(int $id): array { return ["id" => $id]; } } $repo = new FakeRepo(); echo $repo->find(5)["id"];

    Answer

    5

    The fake fills the promised method and returns the id it was asked for.

  6. What does this program print? <?php class Events { private array $listeners = []; public function on(string $name, callable $fn): void { $this->listeners[$name][] = $fn; } public function emit(string $name, array $data): void { foreach ($this->listeners[$name] ?? [] as $fn) { $fn($data); } } } $events = new Events(); $events->on("ping", function (array $data): void { echo "one "; }); $events->on("ping", function (array $data): void { echo "two"; }); $events->emit("ping", []);

    Answer

    one two

    Both callables were appended to the same name and run in the order they were added.

  7. What does this program print? <?php class Events { public function emit(string $name, array $data): void { foreach ($this->listeners[$name] ?? [] as $fn) { $fn($data); } } } $events = new Events(); $events->emit("missing", []); echo "done";

    Answer

    done

    The null coalescing operator gives an empty list, so the loop runs zero times and the last line prints.

  8. What does this program print? <?php interface UserListener { public function onRegistered(array $user): void; } class MailListener implements UserListener { public function onRegistered(array $user): void { echo "mail to " . $user["email"]; } } $listener = new MailListener(); $listener->onRegistered(["email" => "ada@example.com"]);

    Answer

    mail to ada@example.com

    The class fills the method, and the call passes the array the method reads.

  9. Why does the fake repository record its saves in a public array?

    Answer

    So the test can check what was saved

    The test asserts on the recorded calls, which is how a fake proves the behaviour without a real store.

  10. A class depends on a concrete MySqlUserRepo instead of the interface. What is the cost?

    Answer

    The tests need a database, and swapping the store means editing the class

    The dependency on one implementation drags its setup into every test and every future swap.

The examples call count(). The programs on this page were run with PHP 8.5.13 (php -v) with the commands shown above.

Article author: Arthur Isaev