Repository and observer

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.

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

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.

interface UserListener { public function onRegistered(array $user): void; } class MailListener implements UserListener { public function onRegistered(array $user): void { echo "mail to " . $user["email"] . "\n"; } }

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.

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); } } }

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.

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; } }

Next: Testing without frameworks

Автор статьи: Arthur Isaev