Dependency Injection, Coupling and Cohesion: A First Look

12.Dependency Injection, Coupling and Cohesion: A First Look

M

In this chapter

We'll take a first look at dependency injection — giving an object what it needs instead of letting it create it — and why it let a test send 20 real text messages at 11 p.m., plus the two measures of good design, coupling and cohesion, and the rule "favour composition over inheritance".

15–17 min

The Problem in Real Life

Late on Sunday, Mia tests a small change to the reminder code on her laptop. Twenty of Tom's real customers get a text at 11 p.m.: "Reminder: your haircut tomorrow at 9:30." Some of them aren't even booked tomorrow — it was test data.

The reason is one line inside ReminderSender's constructor: $this->sms = new TwilioSms();. The class builds its own real SMS sender, every time, wherever it runs. There's no way to give it a pretend one for testing.

M

I only wanted to test the message text. How do I run this code without sending real texts?

Mia

Creating Your Own Tools vs. Being Given Them

new inside means stuck

A class that creates its own SMS sender always uses that one — in production, in tests, on your laptop.

Given, not made

Pass the sender in through the constructor, and the caller decides: the real one, or a fake that sends nothing.

Loose and focused

Classes that know little about each other (low coupling) and do one job (high cohesion) are easy to change.

Dependency Injection, Coupling and Cohesion: A First Look

How classes get what they need: this chapter is a first look at four design ideas you'll use in every project; Act 22 and the Laravel course go deeper:

  • Dependency injection: objects receive their dependencies instead of creating them.
  • Coupling: how much one class depends on others.
  • Cohesion: how well the parts of one class belong together.
  • Composition over inheritance: prefer "has-a" to "is-a" for reusing behaviour.

The problem with new inside: a dependency is anything a class needs to do its work (chapter 11): ReminderSender needs something that sends texts. When the class creates it itself with new TwilioSms(), it's welded to that one class. It can't send by email instead, it can't run in a test without sending real messages, and changing TwilioSms's constructor breaks ReminderSender. The class has taken a decision — which sender to use — that isn't its business.

Mia's bug: the class creates its own real sender
<?php
declare(strict_types=1);
class TwilioSms
{
public function send(string $to, string $text): void
{
echo "REAL SMS to $to: $text\n"; // in real life: a paid text to a real phone
}
}
class ReminderSender
{
private TwilioSms $sms;
public function __construct()
{
$this->sms = new TwilioSms(); // welded in: no way to swap it
}
public function remind(string $phone): void
{
$this->sms->send($phone, "Reminder: your haircut tomorrow at 9:30.");
}
}
(new ReminderSender())->remind("+447700900456"); // even in a test
// REAL SMS to +447700900456: Reminder: your haircut tomorrow at 9:30.

Dependency injection: the fix is simple: don't create the dependency, ask for it. public function __construct(private Notifier $notifier) {} says "give me something that can send". That's dependency injection (DI): the dependency is injected from outside. Usually it's through the constructor, as here (constructor injection); sometimes it's through a method parameter, for a dependency used only once. The parameter is typed with the interface (chapter 8), so any notifier fits. In production, the code that starts the program passes in the real SMS sender. In a test, or on Mia's laptop, it passes in a FakeNotifier that just collects the messages in an array. No real text can leave. Dependency injection isn't a library or a framework feature; it's a constructor parameter. The diagram below shows who decides what, before and after.

Before and after dependency injection

Before: ReminderSender

decides itself: new TwilioSms() — always the real one

After: the code that starts the program

decides: production or test?

creates / chooses

TwilioSms (welded in)

a test sends 20 real texts

new TwilioNotifier() or new FakeNotifier()

chosen outside

result / injects

Can't be swapped or tested

tight coupling

new ReminderSender($notifier)

only knows Notifier::send() — loose coupling

The fix: inject the dependency, typed with an interface
<?php
declare(strict_types=1);
interface Notifier
{
public function send(string $to, string $text): void;
}
class FakeNotifier implements Notifier // for tests and laptops
{
public array $sent = [];
public function send(string $to, string $text): void
{
$this->sent[] = "$to: $text"; // collects, sends nothing
}
}
class ReminderSender
{
public function __construct(private Notifier $notifier) {} // given, not made
public function remind(string $phone): void
{
$this->notifier->send($phone, "Reminder: your haircut tomorrow at 9:30.");
}
}
$fake = new FakeNotifier();
$sender = new ReminderSender($fake); // the caller decides
$sender->remind("+447700900456");
echo count($fake->sent), " message collected, none sent\n"; // 1 message collected, none sent
echo $fake->sent[0], "\n"; // +447700900456: Reminder: your haircut tomorrow at 9:30.
// In production: new ReminderSender(new TwilioSmsNotifier($apiKey))

DI containers: in a big application, building every object and its dependencies by hand gets long: the reminder sender needs a notifier, which needs an API key and an HTTP client, which needs… A DI container (also called a service container) does that wiring for you: it reads the constructor's type hints and builds what's needed, which is called autowiring. Laravel's service container does exactly this; you'll use it from the first chapter of the next course. Underneath, it's still plain constructor injection.

Coupling: coupling is how much a class depends on the details of other classes. ReminderSender with new TwilioSms() is tightly coupled: it knows the exact class and how to build it. With an injected Notifier, it's loosely coupled: it knows only that something can send(). Loose coupling means a change in one class rarely forces changes in others, and each class can be tested on its own. Interfaces and dependency injection are the main tools for it.

Cohesion: cohesion is how well the parts of one class belong together. A class with high cohesion does one job, and all its methods and properties serve it: Money, Booking, SmsNotifier. A class with low cohesion does many unrelated jobs: a BookingManager that prices bookings, sends texts, makes PDFs and cleans up old data. Such classes grow without end and break in surprising places. Aim for high cohesion and low coupling — small, focused classes that know little about each other. (The "S" of the SOLID principles, Act 22, says the same: a class should have one reason to change.)

Low cohesion: one class doing everything
<?php
// A warning sign — this class has four unrelated reasons to change:
class BookingManager
{
public function price(array $booking): int { /* pricing rules */ return 0; }
public function sendReminder(array $booking): void { /* SMS gateway */ }
public function invoicePdf(array $booking): string { /* PDF layout */ return ""; }
public function deleteOldBookings(): void { /* database clean-up */ }
}
// Split by job — each class small, focused and easy to test:
// Booking::price(), ReminderSender, InvoicePdf, BookingCleanup

Favour composition over inheritance: chapter 7 showed inheritance for real is-a relationships. For reusing behaviour, it's usually the wrong tool. class ReminderSender extends TwilioSms would give the reminder sender every method of the SMS client and tie it to that one class forever; changes in the parent ripple into every child (the "fragile base class" problem), and PHP allows only one parent. Composition — holding the other object in a property and calling it, ideally injected — gives the same reuse with loose coupling: ReminderSender has a Notifier. When you're unsure, choose "has-a". The table below sums up the chapter.

Table — Design ideas from this chapter
IdeaBad signGood sign
Dependency injectionnew TwilioSms() inside the class__construct(private Notifier $notifier)
CouplingThe class knows concrete classes and how to build themThe class knows interfaces only
CohesionBookingManager prices, texts, makes PDFs and cleans upOne class, one job: Money, SmsNotifier, Booking
ReuseReminderSender extends TwilioSmsReminderSender has a Notifier
TestingTests send real messagesTests inject a FakeNotifier
Inheritance for reuse vs. composition
<?php
declare(strict_types=1);
interface Notifier
{
public function send(string $to, string $text): string;
}
class SmsNotifier implements Notifier
{
public function send(string $to, string $text): string
{
return "SMS to $to: $text";
}
}
// Inheritance: ReminderSender IS an SmsNotifier — tied to SMS forever, one parent used up
class InheritingReminder extends SmsNotifier
{
public function remind(string $to): string
{
return $this->send($to, "See you tomorrow.");
}
}
// Composition: ReminderSender HAS a Notifier — any channel, injected
class ReminderSender
{
public function __construct(private Notifier $notifier) {}
public function remind(string $to): string
{
return $this->notifier->send($to, "See you tomorrow.");
}
}
echo (new InheritingReminder())->remind("+447700900123"), "\n";
echo (new ReminderSender(new SmsNotifier()))->remind("+447700900123"), "\n";
// SMS to +447700900123: See you tomorrow.
// SMS to +447700900123: See you tomorrow.

Key Takeaway

Dependency injection means a class receives what it needs — usually through its constructor, typed with an interface — instead of creating it with new. The caller chooses the implementation: the real SMS sender in production, a fake in tests. DI containers like Laravel's do the wiring automatically. Aim for low coupling (classes know little about each other) and high cohesion (each class does one job), and favour composition (has-a) over inheritance (is-a) for reusing behaviour.

Why This Matters

Dependency injection is what makes code testable without side effects — no real texts, charges or emails while you work — and what lets BookBay switch SMS providers by changing one line where objects are built, instead of every class that sends a message.

It's also the foundation of Laravel: almost every class you write there receives its dependencies through its constructor, and the framework's container fills them in. Coupling and cohesion are the two words you'll use for the rest of your career to say why a design is good or bad.

ReminderSender receives its Notifier, and Mia's laptop now uses a FakeNotifier; no customer will get a test text again. One last surprise for the Act: to reschedule Clare's booking, she writes $moved = $booking; $moved->start = "11:00"; — and Clare's original 9:30 booking moves to 11:00 too. Assigning an object didn't copy it. That's the next chapter: object identity, comparison, cloning and serialization.