Skip to content
Tutorials Center
My learning

Topics

Lesson 60 of 147 ยท Object-Oriented PHP

OOP Design Principles

Learn object-oriented design in PHP - the SOLID principles with small examples, composition over inheritance, dependency injection and interfaces for testability.

You now know the whole toolbox of object-oriented PHP: classes, interfaces, traits, enums, readonly properties, hooks and namespaces. Knowing the tools is not the same as building something that's pleasant to change a year later. Two programs can use exactly the same features, and one is easy to extend and test while the other turns every small change into a risky afternoon. The difference is design: how responsibilities are split between classes and how those classes depend on each other.

This lesson collects the principles experienced developers use to make those decisions. The best known are the five SOLID principles. Next to them are three ideas that matter just as much day to day: composition over inheritance, dependency injection and programming to interfaces so code can be tested. Every principle comes with a small PHP example showing the problem and the fix.

Treat these as guidelines, not laws. They exist to make code easier to change. When applying one would make a small, stable piece of code harder to read, the principle has stopped helping you.

Single Responsibility Principle

A class should have one reason to change.

"Responsibility" here means a reason to change, usually a person or team that might ask for changes. Here's a class that does three unrelated jobs:

PHP
class InvoiceService
{
    public function process(array $order): void
    {
        // 1. business rules: calculate the total with tax
        // 2. presentation: build an HTML email
        // 3. infrastructure: write to the database and send the email via SMTP
    }
}

The accountant changes the tax rules, the designer changes the email layout, the operations team moves to a different mail provider, and every one of those requests means editing the same class and risking the other two jobs. Splitting it gives each reason to change its own home:

PHP Splitting responsibilities

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Each class is small, has an obvious name, and can be tested on its own: you can check the tax maths without building any HTML. A useful smell test: if you need the word "and" to describe what a class does ("it calculates totals and formats emails and sends them"), it probably has more than one responsibility.

Open/Closed Principle

Software should be open for extension but closed for modification.

You should be able to add new behavior by adding new code, not by editing working code. The classic violation is a growing switch or match on a type:

PHP
function shippingCost(string $method, float $kg): float
{
    return match ($method) {
        'standard' => 4.99 + $kg * 0.5,
        'express' => 9.99 + $kg * 1.2,
        // every new carrier means editing (and re-testing) this function
    };
}

Moving each variation behind an interface means a new carrier is a new class, and the code that uses carriers never changes:

PHP Extending with new classes instead of edits

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

This is the strategy pattern, covered with others in Design Patterns in PHP. Don't apply it everywhere, though. A match over a closed enum that rarely changes is perfectly fine, and is often clearer than five tiny classes. Open/closed pays off where variations really do keep arriving: payment providers, export formats, notification channels.

Liskov Substitution Principle

Objects of a subclass must be usable anywhere the parent is expected, without surprises.

If code works with a Parent, it must keep working when handed a Child. Type compatibility is checked by PHP (a child can't change a method's signature incompatibly), but behavior isn't. The textbook example is a Square that extends Rectangle:

PHP A subclass that breaks expectations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

stretch() was written for rectangles and is correct for them, but a Square returns 16 instead of 20. Geometrically a square is a rectangle, yet a mutable Square can't keep the promises a mutable Rectangle makes. Fixes include making both immutable value objects (then "set width" returns a new Rectangle), or giving both a common Shape interface without the inheritance.

Signs that a subclass violates Liskov: it throws "not supported" from an inherited method, it ignores arguments, it demands stricter input than the parent, or callers start writing if ($x instanceof Square). PHP helps on the type level by enforcing that parameter types may only widen and return types may only narrow in child classes; that's covered in The PHP Type System in Depth.

Interface Segregation Principle

Clients shouldn't be forced to depend on methods they don't use.

Big "do everything" interfaces force implementers to write empty or throwing methods. Prefer several small, focused interfaces. A class can implement as many as it needs:

PHP
// Too big: a read-only CSV source must still "implement" save() and delete()
interface Repository
{
    public function find(int $id): ?array;
    public function all(): array;
    public function save(array $record): void;
    public function delete(int $id): void;
}

// Better: small roles
interface ReadsRecords
{
    public function find(int $id): ?array;
    public function all(): array;
}

interface WritesRecords
{
    public function save(array $record): void;
    public function delete(int $id): void;
}

final class CsvProductSource implements ReadsRecords { /* ... */ }
final class DatabaseProducts implements ReadsRecords, WritesRecords { /* ... */ }

A report generator now type-hints ReadsRecords and works with both, and it's obvious from its signature that it never writes anything. PHP's own interfaces follow this idea: Countable, IteratorAggregate, ArrayAccess, Stringable and JsonSerializable each describe one ability (see Abstract Classes and Interfaces).

Dependency Inversion Principle

High-level code should depend on abstractions, not on low-level details.

Business logic ("send a welcome message when someone registers") shouldn't know how messages are delivered. If the registration class creates an SmtpMailer itself, it's welded to SMTP: you can't switch to an API-based provider, and you can't test registration without sending real email.

Inverting the dependency means the high-level code declares the interface it needs, and the low-level details implement it. Then the dependency is injected from outside, usually through the constructor:

PHP Depending on an interface, injected through the constructor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

RegistrationService never mentions SMTP. Swapping providers means writing another Mailer implementation and changing one line where objects are created. That place, which builds the object graph, is called the composition root; in frameworks, a dependency injection container does that wiring automatically (you'll build a tiny one in Reflection).

Dependency injection and testability

Dependency injection (DI) simply means: a class receives the objects it needs instead of creating or fetching them itself. Constructor injection, as above, is the most common form. The alternatives that DI replaces are:

  • new SmtpMailer() inside the class: a hidden, hard-coded dependency.
  • Global state or static calls like Mailer::send(...) or global $mailer;: invisible in the constructor, impossible to swap safely (see Static Properties and Methods).
  • A service locator ($container->get('mailer') inside the class): the dependency is still hidden.

The biggest payoff is testing. Because RegistrationService depends on the Mailer interface, a test can pass in a fake that records messages instead of sending them:

PHP Testing with a fake implementation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Both tests pass without a mail server, run in microseconds and check exactly the behavior that matters. assert() throws an AssertionError when a condition is false (assertions are enabled in our editor). Real projects use PHPUnit or Pest for this, as shown in Testing PHP Code, but the design idea is the same: code that receives its dependencies can be tested; code that creates them usually can't.

Composition over inheritance

Inheritance ("is a") is the tightest coupling there is: a child class depends on its parent's internals, and a change in the parent can break every child. Deep hierarchies such as Animal โ†’ Bird โ†’ FlyingBird โ†’ Parrot also collapse when reality doesn't fit (penguins, robot birds). Composition ("has a") builds behavior by combining small objects instead:

PHP Composing behavior with decorators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

With inheritance, "prefixed, deduplicated console notifier" would need its own subclass, and so would every other combination. With composition, each behavior is one small class, combinations are made at run time, and the duplicate message is filtered without ConsoleNotifier knowing anything about it. This wrapping technique is the decorator pattern.

Inheritance is still right when there's a true "is a" relationship and the parent was designed to be extended, such as an abstract base class with template methods. Many teams make classes final by default and remove final only when extension is intentional. Traits share code too, but they're a copy-paste mechanism, not a design tool, so prefer composition for behavior.

Other principles worth knowing

  • Tell, don't ask. Instead of if ($account->getBalance() >= $amount) { $account->setBalance(...); }, write $account->withdraw($amount) and let the object enforce its rules. This is encapsulation, and asymmetric visibility makes it easy.
  • Make invalid states unrepresentable. Validate in constructors and use value objects and enums so a half-valid object can't exist.
  • Law of Demeter. Avoid long chains like $order->getCustomer()->getAddress()->getCountry()->getTaxRate(); each dot is a dependency on another class's structure.
  • KISS and YAGNI ("keep it simple" and "you aren't gonna need it"). Don't add interfaces, factories and layers for variations that don't exist yet. Add the abstraction when the second real use case appears.
  • DRY ("don't repeat yourself") is about knowledge, not text. Two similar-looking snippets that change for different reasons aren't duplication; merging them couples unrelated things.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A class calculates order totals, renders a PDF and uploads it to cloud storage. Which principle does it most clearly violate?

    It has three different reasons to change (pricing rules, layout, storage provider), so it should be split into separate classes.
  2. 2. A subclass overrides save() to throw "Read-only records can't be saved". Which principle is at risk?

    Code written for the parent expects save() to work. A child that refuses breaks that promise, so it can't safely replace the parent.
  3. 3. What does dependency injection mean?

    With DI, dependencies are passed in from outside, which makes them visible, swappable and easy to replace with fakes in tests.
  4. 4. Why does depending on a Mailer interface instead of SmtpMailer make RegistrationService easier to test?

    The service only needs something that implements Mailer, so tests can provide a simple recording double and check what would have been sent.
  5. 5. You need notifiers that can be prefixed, deduplicated, or both, in any combination. Which design scales best?

    Composition lets you combine behaviors at run time without a subclass for each combination, and each class stays small and testable.

Summary

  • Single Responsibility: one reason to change per class; split business rules, presentation and infrastructure.
  • Open/Closed: add new behavior with new classes behind an interface instead of editing a growing switch/match, where variations really keep coming.
  • Liskov Substitution: a child must keep the parent's promises; throwing "not supported" or needing instanceof checks is a warning sign.
  • Interface Segregation: prefer small, role-based interfaces that classes combine.
  • Dependency Inversion: high-level code depends on interfaces; concrete classes are chosen in one composition root.
  • Dependency injection passes collaborators in, usually through the constructor, which makes code flexible and testable with fakes.
  • Composition over inheritance: build behavior by combining small objects; keep inheritance for true, designed "is a" relationships.
  • These are guidelines to make change easy. Keep it simple and add abstractions when real needs appear.

Next: Errors, Warnings and Notices