Strategy and factory

A pattern is a small arrangement of PHP classes that keeps one rule in one place. The strategy and the factory below are built and called in the examples, so the discount each one computes is on the page as a number from a run.

Strategy

A strategy hides one varying rule behind a shared interface, so the caller never learns which variant runs. Adding a new discount means adding a class, not editing every checkout branch.

<?php interface Discount { public function apply(float $total): float; } class VipDiscount implements Discount { public function apply(float $total): float { return $total * 0.9; } } $discount = new VipDiscount(); echo $discount->apply(200.0), PHP_EOL;

php strategy.php

180

The object owns the rule, and the caller only knows the interface. A second class with the same method would slot in without a line of change at the call site.

Simple factory

A factory keeps object creation in one named place instead of scattering new calls across the codebase. Callers ask for a kind and receive a ready strategy without knowing class names.

<?php interface Discount { public function apply(float $total): float; } class VipDiscount implements Discount { public function apply(float $total): float { return $total * 0.9; } } function makeDiscount(string $kind): Discount { if ($kind === "vip") { return new VipDiscount(); } throw new InvalidArgumentException("Unknown kind: " . $kind); } $discount = makeDiscount("vip"); echo get_class($discount), PHP_EOL; echo $discount->apply(200.0), PHP_EOL; try { makeDiscount("gold"); } catch (InvalidArgumentException $e) { echo $e->getMessage(), PHP_EOL; }

php factory.php

VipDiscount
180
Unknown kind: gold

The factory returned the right strategy for the string, and the unknown kind left through the exception with the message the catch arm prints.

Replace switch

Long switches on the same kind string are factories crying for help. Build the object once at the edge, then let polymorphism carry the value through the rest of the flow.

<?php interface Discount { public function apply(float $total): float; } class VipDiscount implements Discount { public function apply(float $total): float { return $total * 0.9; } } function makeDiscount(string $kind): Discount { if ($kind === "vip") { return new VipDiscount(); } throw new InvalidArgumentException("Unknown kind: " . $kind); } $kind = "vip"; $discount = makeDiscount($kind); $total = $discount->apply(200.0); echo $total . "\n";

php replace.php

180

The choice of rule happens once, in the factory call, and the line after it knows only that something can apply a total.

When patterns pay

Patterns cost files and names, so spend them where variants multiply: pricing rules, shipping rules, export formats. With one variant only, a plain function wins. With three or more, strategies and factories pay rent.

<?php interface Discount { public function apply(float $total): float; } class VipDiscount implements Discount { public function apply(float $total): float { return $total * 0.9; } } function makeDiscount(string $kind): Discount { if ($kind === "vip") { return new VipDiscount(); } throw new InvalidArgumentException("Unknown kind: " . $kind); } function checkoutTotal(string $kind, float $total): float { return makeDiscount($kind)->apply($total); } echo checkoutTotal("vip", 200.0) . "\n";

php checkout.php

180

One line at the edge of the checkout and no branch afterwards. Add a second class and a second arm in the factory, and this function still does not change.

Exercises

  1. Add a NoDiscount class that returns the total unchanged.
  2. Add its arm to the factory and call it with the kind none.
  3. Give the product a plain function version with one if and compare the line count.
  4. Make the factory throw for an empty kind and catch it in the caller.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does a strategy object hide?

    Answer

    One varying rule behind a shared interface

    The caller sees only the interface, so it never learns which variant answered.

  2. Where does a factory keep the knowledge of class names?

    Answer

    In one creation function

    One named place builds the objects, and the rest of the code asks for a kind.

  3. What replaces a long switch on a kind string?

    Answer

    An object built once at the edge, with polymorphism after it

    The choice happens once, and the rest of the flow calls the shared method.

  4. When does a pattern cost more than it returns?

    Answer

    When there is only one variant

    A single rule is one function; the extra classes and names earn their place only with real variety.

  5. What does this program print? <?php interface Discount { public function apply(float $total): float; } class VipDiscount implements Discount { public function apply(float $total): float { return $total * 0.9; } } $discount = new VipDiscount(); echo $discount->apply(200.0);

    Answer

    180

    Ninety percent of two hundred is one hundred eighty.

  6. What does this program print? <?php interface Discount { public function apply(float $total): float; } class HalfOff implements Discount { public function apply(float $total): float { return $total * 0.5; } } echo (new HalfOff())->apply(80.0);

    Answer

    40

    Half of eighty is forty, and the interface method returns it as a float that prints without a decimal part.

  7. What does this program print? <?php interface Discount { public function apply(float $total): float; } class VipDiscount implements Discount { public function apply(float $total): float { return $total * 0.9; } } function makeDiscount(string $kind): Discount { if ($kind === "vip") { return new VipDiscount(); } throw new InvalidArgumentException("Unknown kind: " . $kind); } echo get_class(makeDiscount("vip"));

    Answer

    VipDiscount

    The factory builds the vip strategy, and get_class() names the class of that object.

  8. What does this program print? <?php function makeDiscount(string $kind): string { if ($kind === "vip") { return "vip"; } throw new InvalidArgumentException("Unknown kind: " . $kind); } try { makeDiscount("gold"); } catch (InvalidArgumentException $e) { echo $e->getMessage(); }

    Answer

    Unknown kind: gold

    The factory throws with the kind in the message, and the catch arm prints it.

  9. Why does the caller of a strategy not need a branch for each variant?

    Answer

    Because PHP resolves the method at run time on the object it holds

    The object knows its own class, so the same call reaches the right method without help from the caller.

  10. A factory returns an object of an unknown kind instead of throwing. What goes wrong at the call site?

    Answer

    A method the interface promises is missing, and the call fails

    The return type promises the interface, so an object without its method breaks the next call or the type check.

The examples call get_class(). The programs on this page were run with PHP 8.5.13 (php -v) with the commands shown above.

Article author: Arthur Isaev