Inversion of control: replace hand-wired flow with hooks
Write a rule for every job once, and let each job fill in its part.
Watch the narrated video
Every step
Problem
Steps 1–4Refactor
Steps 5–11Payoff
Steps 12–13PHP bonus
Steps 14–16Recap
Steps 17–18The code: before and after
Before
declare(strict_types=1);
final class ShipmentJob
{
/** @param list<int> $shipmentIds */
public function run(array $shipmentIds): void
{
echo 'ship: start' . PHP_EOL;
foreach ($shipmentIds as $id) {
echo "label {$id}" . PHP_EOL;
}
echo 'ship: done, items: ' . count($shipmentIds) . PHP_EOL;
}
}
final class RefundJob
{
/** @param list<int> $refundIds */
public function run(array $refundIds): void
{
echo 'refund: start' . PHP_EOL;
foreach ($refundIds as $id) {
echo "refund {$id}" . PHP_EOL;
}
echo 'refund: done, items: ' . count($refundIds) . PHP_EOL;
}
}
(new ShipmentJob())->run([101, 102]);
(new RefundJob())->run([7]);After
declare(strict_types=1);
final class BatchRunner
{
/** @param list<int> $ids */
public function run(string $name, array $ids, Closure $handle): void
{
echo "{$name}: start" . PHP_EOL;
foreach ($ids as $id) {
$handle($id);
echo "audit {$name} {$id}" . PHP_EOL;
}
echo "{$name}: done, items: " . count($ids) . PHP_EOL;
}
}
final class ShipmentJob
{
public function handle(int $id): void
{
echo "label {$id}" . PHP_EOL;
}
}
final class RefundJob
{
public function handle(int $id): void
{
echo "refund {$id}" . PHP_EOL;
}
}
$runner = new BatchRunner();
$runner->run('ship', [101, 102], (new ShipmentJob())->handle(...));
$runner->run('refund', [7], (new RefundJob())->handle(...));
$runner->run('restock', [55], function (int $id): void {
echo "restock {$id}" . PHP_EOL;
});Transcript, step by step
Problem
Step 1: Two jobs, two loops Before
These are a warehouse's night batches, and Shipment Job echoes a start line, one label per item, and a done line. Refund Job does the same with its own words, a start line, one refund line per item, and a done line. The script ships items 101 and 102, then refunds item 7, so the night prints seven lines. Each job was small and written on a different day, so writing the loop out in each one was the shortest path. So any rule for every batch now has two loops to land in.
Step 2: An audit line per item Change request
Now compliance asks that every batch write one audit line per item, right after the item is handled. The quick way adds an audit echo inside Shipment Job's loop, and another one inside Refund Job's loop. It runs, and the output gains audit ship 101, audit ship 102, and audit refund 7.
Step 3: Every job wires the flow Code smell
The fixed order of a batch, a start line, the work for each item, and a done line, is its flow. Here each job wires that flow by hand, so a rule for every batch has to be written into every job. You can see it in the shipment loop here, its audit line here, the refund loop here, and its audit line here. The same audit rule now exists twice, and each new job means pasting it into one more loop. If one copy forgets the audit line, nothing stops it, and that batch runs silently unaudited.
Step 4: Flip who runs the loop Principle
You might extract an audit helper, but each loop would still have to call it. Forget that call in one job, and that batch still runs unaudited. So the loop should live in one place, and each job should only say what happens to one item. The fix flips who runs the loop, so one runner runs it and calls each job.
Refactor
Step 5: Refactor first Back it out
So we take both audit lines back out, and the jobs print their seven lines again. We refactor in small steps with the same output each time, and the audit comes back at the end.
Step 6: Shipment's per-item work Extract Method
In Shipment Job, we extract the label echo into its own method, handle, which takes one item id. The loop now calls handle for each id, and the output is the same.
Step 7: Refund's per-item work Extract Method
Refund Job's loop does the same per-item work, so it gets the same move, a handle method. Its loop calls handle for each id, and both jobs now keep their per-item work in one method.
Step 8: Name the hook Extract Interface
Both handle methods have the same shape, so we extract an interface, Batch Step, with that one method. Shipment Job and Refund Job both implement it. Nothing calls handle through the interface yet, so each job still runs its own loop.
Step 9: A runner owns the flow Extract Class
Now we extract a class, Batch Runner, and move the flow into its run method. It takes a batch name, the ids and a Batch Step, then echoes the start line, loops, and echoes the done line. Inside the loop, it calls the step's handle for each id. A method the runner calls at a fixed point in its flow is a hook, and each job fills it in. Shipment Job's run now only hands its name, its ids and itself to the runner. So the runner now calls Shipment Job, not the other way round, and that flip is inversion of control. The output still matches the first version, line for line.
Step 10: Refund uses the runner Replace Inline Code with Function Call
Refund Job's run still wrote the same flow by hand, so we replace that code with a call to the runner. It passes refund, its ids and itself, and the output stays the same.
Step 11: Each job is only its hook Inline Method
Both run methods only forwarded to the runner, so we inline them into the script and delete them. The script builds one Batch Runner and runs ship and refund, each with its ids and a new job. Each job is now only its hook, one handle method that says what happens to one item.
Payoff
Step 12: The audit, take two Payoff
So the audit request from the start can come back in now. It's one line in Batch Runner's loop, right after the step handles the item. The output is the same as the quick version, with audit ship 101, audit ship 102, and audit refund 7. Shipment Job and Refund Job didn't change at all. Where the shipment loop and its audit line stood, there's only a handle method now, and the same goes for refund. So now the audit lives in one loop, and both jobs are only hooks.
Step 13: A third job Payoff
But the real test is a new job, and Restock Job has only a handle method that echoes restock and the id. The script runs it with item 55 under the name restock. Restock Job has no loop and no audit line of its own, so what does its batch print? Its batch still prints restock 55 and then audit restock 55, because that line comes from the runner's loop. The runner owns the flow and calls each job's hook, so a rule for every batch is one edit in one place. But every job must now fit the runner's one flow, and a job with a different order can't use it. You also read two classes to follow one batch.
PHP bonus
Step 14: A class for one echo PHP bonus
But Restock Job is a whole class, seven lines long, for one echo. In PHP, every anonymous function is a Closure object, so the runner can take a Closure instead of the interface.
Step 15: A job as a closure PHP bonus
So Batch Runner's run now takes a Closure called handle, and calls it for each id. Shipment Job and Refund Job stay named classes, and the script turns their handle methods into closures with the three dots syntax. The restock job becomes an anonymous function, written right where the script runs it, and the Restock Job class is gone. The output is the same, audit line included, because the runner still calls each job's code at the same point. But a Closure holds only one function, so a job that needs a second hook brings the interface back.
Step 16: Drop the unused interface Remove Dead Code
Nothing takes a Batch Step anymore, so we delete the interface and the two jobs stop implementing it. The output doesn't change, because the runner stopped using the interface in the last step.
Recap
Step 17: Where we started, where we ended Before / after
On the left, each job ran its own flow, with its own start line, loop, and done line. So a rule for every batch, like the audit line, had to be pasted into each loop. On the right, Batch Runner owns the flow and calls each job's hook, with the audit written once. And each job, even the closure, only fills in what happens to one item.
Step 18: When to reach for it Takeaways
Reach for it when several jobs share one fixed flow and differ only in the work they do per item. Skip it when there's one job, or when the flows really run in a different order. A runner then only adds a second place to read, with nothing shared for it to own. Spot it by the same loop, with the same start and done lines, copied into several classes. And PHP's own usort works this way, because it owns the sort and calls your comparison function to decide the order.