I'll Be Backend
Principles · PHP

Hollywood Principle: stop polling, let the framework call you

Let Checkout tell each part about every order, so none is missed.

17 steps5 chapters~7 min at 1.25×#hollywood principle#observer#polling#listeners
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–5

Refactor

Steps 6–11

Payoff

Step 12

PHP bonus

Steps 13–15

Recap

Steps 16–17

The code: before and after

Before

declare(strict_types=1);

final class Checkout
{
    /** @var list<int> */
    private array $orders = [];

    public function place(int $id): void
    {
        $this->orders[] = $id;
    }

    /** @return list<int> */
    public function openOrders(): array
    {
        return $this->orders;
    }
}

final class Packing
{
    private int $lastSeen = 0;

    public function check(Checkout $checkout): void
    {
        $open = $checkout->openOrders();
        foreach (array_slice($open, $this->lastSeen) as $id) {
            echo "pack {$id}" . PHP_EOL;
        }
        $this->lastSeen = count($open);
    }
}

final class Invoicing
{
    private int $lastSeen = 0;

    public function check(Checkout $checkout): void
    {
        $ids = $checkout->openOrders();
        foreach (array_slice($ids, $this->lastSeen) as $id) {
            echo "invoice {$id}" . PHP_EOL;
        }
        $this->lastSeen = count($ids);
    }
}

$checkout = new Checkout();
$packing = new Packing();
$invoicing = new Invoicing();
// tick 1
$checkout->place(101);
$packing->check($checkout);
$invoicing->check($checkout);
// tick 2
$checkout->place(102);
$packing->check($checkout);
$invoicing->check($checkout);
// tick 3
$packing->check($checkout);
$invoicing->check($checkout);

After

declare(strict_types=1);

final class Checkout
{
    /** @var list<int> */
    private array $orders = [];
    /** @var list<Closure> */
    private array $listeners = [];

    public function subscribe(Closure $listener): void
    {
        $this->listeners[] = $listener;
    }

    public function place(int $id): void
    {
        $this->orders[] = $id;
        foreach ($this->listeners as $listener) {
            $listener($id);
        }
    }

    public function cancel(int $id): void
    {
        $this->orders = array_values(array_diff($this->orders, [$id]));
    }

    /** @return list<int> */
    public function openOrders(): array
    {
        return $this->orders;
    }
}

final class Packing
{
    public function orderPlaced(int $id): void
    {
        echo "pack {$id}" . PHP_EOL;
    }
}

$checkout = new Checkout();
$packing = new Packing();
$checkout->subscribe($packing->orderPlaced(...));
$checkout->subscribe(function (int $id): void {
    echo "invoice {$id}" . PHP_EOL;
});
$checkout->place(101);
$checkout->place(102);
$checkout->cancel(101);
$checkout->place(103);

Transcript, step by step

Problem

Step 1: Two parts that poll Before

This is a shop's checkout, and placing an order adds its id to a list of open orders. Packing asks Checkout for that list, echoes pack for every id past last seen, then moves last seen to the end. Invoicing does the same, with invoice instead of pack. The script runs three ticks, and each tick may place an order, then lets both parts check for new ones. Tick three places nothing, so both checks find nothing new, and the output is pack and invoice for 101 and 102. Both parts poll Checkout here, asking it each tick whether anything is new. Checkout knows nothing about packing or invoicing, and asking each tick was the shortest way to find new orders.

Step 2: Customers can cancel Change request

Now customers can cancel an order, and a cancelled order leaves the open list. The quick edit adds a cancel method to Checkout, which removes that id and renumbers the list from zero. Tick three now cancels order 101 and places order 103, then lets packing and invoicing check as before. The script runs, so what does tick three echo? Nothing at all, so order 103 is never packed and never invoiced, and no error tells us.

Step 3: A guess from the length Code smell

After the cancel and the new order, the list is two long, and last seen is still two. Each part polls Checkout and guesses what's new from the list's length. So when a cancel and a new order land between two polls, they hide each other from that guess. You can see it in Packing's loop here, the same loop in Invoicing here, and the cancel that breaks it here. Order 103 is never packed and never invoiced, yet the script runs without a single error. And the same guess lives in each part, so a fix has to be made in every poller.

Step 4: Let the source call Principle

We could fix the guess in both loops, but every new poller would have to repeat that fix. Only Checkout knows the moment an order exists, so Checkout should call each part at that moment. Low-level parts don't call the source to ask, the source calls them, and that rule is the Hollywood Principle. Its short form is don't call us, we'll call you. So now: Checkout must call each part, and no part asks.

Step 5: Refactor first Back it out

So we take cancel back out, and tick three is an empty poll again. We refactor first in small steps, with the same four lines of output each time, and cancel comes back at the end.

Refactor

Step 6: Packing's work per order Extract Method

So in Packing, we extract the echo into its own method, order placed, which takes one order id. The loop now calls order placed for each new id, and the output is the same.

Step 7: Invoicing's work per order Extract Method

Invoicing gets the same move, with its invoice echo in its own order placed method. Its loop calls that method too, and the output still has the same four lines.

Step 8: Name the listener Extract Interface

Both methods have the same shape, so we extract an interface, Order Listener, with that one method. Packing and Invoicing now implement it, though nothing calls them through the interface yet.

Step 9: Checkout calls Packing Apply Observer

Now Checkout keeps a list of listeners, and its subscribe method adds one to that list. After place adds the id, it calls order placed on every listener, and that call is a notification. Checkout calls listeners it only knows through one interface, and that design is the Observer pattern. In that pattern, Checkout plays the Subject and Packing plays an Observer. The script subscribes Packing and stops calling its check, and each tick still echoes pack before invoice.

Step 10: Checkout calls Invoicing Apply Observer

Invoicing gets the same move, so the script subscribes it and stops calling its check. Now no part asks Checkout anything, because Checkout calls each listener from the loop in place. Invoicing is an Observer too, and the output is still the same four lines.

Step 11: Delete the polling Remove Dead Code

Both check methods and both last seen properties had no callers left, so nothing polls Checkout anymore. So we delete them, and the script shrinks to two subscribes and two orders, with the same four lines out.

Payoff

Step 12: Cancel, take two Payoff

So now cancel comes back, the same method in Checkout as before. The script places 101 and 102, then cancels 101 and places 103, just like the old tick three. What does the output say about order 103 this time? Pack 103 and invoice 103, because place calls each listener the moment the order exists. Packing and Invoicing didn't change at all. Where Packing's loop and Invoicing's loop guessed, there's no loop now, and cancel can't hide 103 anymore. The parts stopped calling Checkout and Checkout calls them, just as the Hollywood Principle says. But to follow one order now, you read the loop in place and then every listener it calls.

PHP bonus

Step 13: A class for one echo PHP bonus

But Invoicing is a whole class, seven lines long, for one echo, the same weight Restock Job had last lesson. In PHP, every anonymous function is a Closure object, so Checkout can keep Closures instead of listeners.

Step 14: A listener as a closure PHP bonus

So subscribe now takes a Closure, and place calls each one with the order id. Packing stays a named class, and the script turns its order placed method into a Closure with the three dots syntax. Invoicing becomes an anonymous function, written where the script subscribes it, and the Invoicing class is gone. The output is the same, because place still calls every listener the moment the order exists.

Step 15: Drop the unused interface Remove Dead Code

Nothing takes an Order Listener anymore, so we delete the interface and Packing stops implementing it. The output doesn't change, because Checkout stopped using the interface in the last step. But a Closure holds only one function, so a listener that needs a second method brings the interface back.

Recap

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

On the left, Packing and Invoicing each polled Checkout and guessed new orders from the list's length. So a cancel between two polls could hide a brand-new order from both of them. On the right, Checkout calls every listener the moment an order is placed. And each listener, even the anonymous function, only says what happens to one order.

Step 17: When to reach for it Takeaways

Reach for it when several parts must react to something that happens in one place. If nothing can call you back, like an outside API with no webhook, you have to keep asking. Spot it by a counter like last seen, or a loop that asks the source whether anything is new. PHP itself works this way, because it calls every shutdown function you register when your script ends.