Object-Oriented PHP

PHP Object-Oriented Programming Snippets

A small dependency-injection example using interfaces and immutable date values.

Overview

A small dependency-injection example using interfaces and immutable date values.

Code example

<?php
declare(strict_types=1);
interface Clock { public function now(): DateTimeImmutable; }
final class SystemClock implements Clock {
    public function now(): DateTimeImmutable { return new DateTimeImmutable('now',new DateTimeZone('UTC')); }
}
final class ReportService {
    public function __construct(private Clock $clock) {}
    public function generatedAt(): string { return $this->clock->now()->format(DateTimeInterface::ATOM); }
}

How to use it

Place the snippet in a namespaced helper or service file, adapt its inputs to your application and add tests for expected and edge-case behavior.

Notes

The example is intentionally small. Validate untrusted input, handle exceptions and document any PHP extension or database requirements.