I'll Be Backend
Principles · PHP

Object-oriented programming: turn a script into objects

Keep each piece of data with the rules that use it, so features stop copying code.

14 steps5 chapters~5 min at 1.25×#oop#objects#classes#parallel arrays
The lesson plays right here. Pause anywhere, step back, or jump to a step below. Watch the PHP video on YouTube Code on GitHub

Watch the narrated video

Every step

Problem

Steps 1–3

Refactor

Steps 4–8

Payoff

Steps 9–10

PHP bonus

Steps 11–12

Recap

Steps 13–14

The code: before and after

Before

declare(strict_types=1);

$names = ['Ana', 'Ben', 'Cara'];
$plans = ['basic', 'pro', 'pro'];
$months = [3, 12, 2];
for ($i = 0; $i < count($names); $i++) {
    $price = $plans[$i] === 'pro' ? 30 : 10;
    $total = $price * $months[$i];
    echo "{$names[$i]} owes {$total}\n";
}

After

declare(strict_types=1);

final class Subscription
{
    public function __construct(
        public string $name,
        public string $plan,
        public int $months,
    ) {
    }

    public function monthlyPrice(): int
    {
        return $this->plan === 'pro' ? 30 : 10;
    }

    public function total(): int
    {
        return $this->monthlyPrice() * $this->months;
    }
}

$subs = [
    new Subscription('Ana', 'basic', 3),
    new Subscription('Ben', 'pro', 12),
    new Subscription('Cara', 'pro', 2),
];
foreach ($subs as $s) {
    echo "{$s->name} owes {$s->total()}\n";
}
foreach ($subs as $s) {
    if ($s->total() > 100) {
        echo "Reminder: {$s->name}\n";
    }
}

Transcript, step by step

Problem

Step 1: A gym bills its members Before

This gym keeps its members in three arrays, one for names, one for plans and one for months. The loop walks them by index, picks a monthly price from the plan, and multiplies it by the months. Then it echoes each bill, so Ana owes 30, Ben owes 360 and Cara owes 60.

Step 2: Add a reminder Code smell

The front desk now wants a reminder for every member who owes more than 100. The quick way is a second loop that copies the price and total lines, then echoes a reminder for the big bills.

Step 3: Parallel arrays, a rule in a loop Code smell

In a script, the data sits in parallel arrays that belong together only by position, and the rule that turns them into a bill lives inside one loop, so nothing else can use it. You can see the price rule here and copied here, the total here and copied here, and one member spread across three arrays here. When the pro plan goes up to 35, two lines must change, and the one you miss keeps the old 30. So Ben's bill would say 420, while his reminder still works from 360. And every new detail about a member, like a start date, is a fourth array that must stay in the same order as the other three.

Refactor

Step 4: Refactor first Back it out

Let's take the second loop out again. We'll refactor first, so that adding the reminder becomes a small change, and then we'll add it.

Step 5: One member, one object Replace Array with Object

First, a class called Subscription holds the three things we know about a member, its name, its plan and its months. Its constructor takes those three values and assigns each one to its typed property. The three arrays become one array of three Subscription objects. The loop is now a foreach with no index, and it reads s plan and s months. One member is now one object, so its name, plan and months can't drift apart.

Step 6: Name the bill rule Extract Function

The price and total lines move into a plain function called total, which takes one subscription. The loop echoes total of s, and every bill comes out the same as before.

Step 7: Move total to its data Move Method

Total only ever read the subscription's own plan and months, so it moves into Subscription as a method. It loses its parameter and reads this plan instead, because the properties it needs belong to the object it's called on. The loop now asks s for its total. Now the data and the rule that uses it live in one place, and that is what an object is.

Step 8: Give the price a name Extract Method

The price rule gets its own method, monthly price, which returns 30 for pro and 10 for any other plan. Total becomes monthly price times months, so the rule now has a name you can read and call.

Payoff

Step 9: Add the reminder again Payoff

Now the reminder goes in as a second loop that asks each subscription for its total. Subscription didn't change, and neither did the bill loop. Ben owes 360, so he's the one member who gets a reminder.

Step 10: One home for each rule Payoff

The price rule is in one place now, the total is in one place, and each member is one object. A pro price of 35 is one edit in monthly price, and both the bill and the reminder pick it up. A new member detail, like a start date, is one new property on one class instead of a fourth array kept in order. Each member's name, plan and months now sit in one object with the rules that read them, and that is object-oriented programming in this code.

PHP bonus

Step 11: Every property named three times PHP bonus

The class names each property three times, once in its declaration, once as a constructor parameter and once in the assignment. Since PHP 8, constructor property promotion declares and assigns a property straight from the constructor parameter, so each name appears once.

Step 12: Promote the properties PHP bonus

The constructor now lists name, plan and months once, each with public and its type in front. The three new Subscription calls still work as they are, because the parameters keep the same order. Monthly price and total didn't change, and the loops still read s name.

Recap

Step 13: Where we started, where we ended Before / after

On the left, three arrays hold each member by position, and the loop works out the price and the total inline. On the right, one Subscription class holds a member, and it owns the monthly price and total rules. The bill loop asks each subscription for its total, and it never sees the price rule.

Step 14: When to reach for it Takeaways

Reach for objects when a few values always travel together and several parts of the code compute from them. Skip them for a one-off script that runs once, because when nothing else uses its rules, a few lines top to bottom do the job. You'll spot the need by parallel arrays matched by index, and by the same calculation copied into a second loop. PHP's own Date Time class works this way, because it keeps a date together with methods like modify.