The strategy pattern selects interchangeable algorithms behind a small stable interface.
What It Does
The strategy pattern selects interchangeable algorithms behind a small stable interface. The following examples distinguish a normal use case, a boundary case and a practical application.
Requirements and Compatibility
PHP 8.x and a local test environment. Apply input validation, correct error handling and the requirements of any optional libraries.
The code focuses on the core concept. Production implementation may also need routes, validation, persistence, authorization or deployment tooling.
Example 1: Basic Behavior
Understand the primary operation and its inputs.
<?php
interface PriceRule { public function apply(int $cents): int; }
class TenPercentOff implements PriceRule { public function apply(int $cents): int { return (int) round($cents * 0.9); } }
function total(PriceRule $rule, int $cents): int { return $rule->apply($cents); }
echo total(new TenPercentOff(), 1000);
Example 2: Another Case
Check failure behavior or a different execution path.
<?php
interface Sorting { public function sort(array $items): array; }
class NumericSorting implements Sorting { public function sort(array $items): array { sort($items, SORT_NUMERIC); return $items; } }
print_r((new NumericSorting())->sort([8, 2, 4]));
Practical Example: Putting It to Use
Apply the behavior in a small, controlled scenario.
<?php
interface Shipping { public function fee(int $weight): int; }
class FlatShipping implements Shipping { public function fee(int $weight): int { return 250; } }
function quote(Shipping $method): int { return $method->fee(2); }
echo quote(new FlatShipping());
Important Behavior and Edge Cases
Keep strategies side-effect-aware and injectable so they can be independently tested.
Comparison with Related Functions or Approaches
| Option | What it means in practice |
|---|---|
| Applying the Strategy Pattern in PHP | The strategy pattern selects interchangeable algorithms behind a small stable interface. |
| Related approach | A decorator adds behavior to one implementation rather than choosing an algorithm. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Ignoring the important boundary for Applying the Strategy Pattern in PHP | Keep strategies side-effect-aware and injectable so they can be independently tested. |
| Assuming a related mechanism has the same behavior | A decorator adds behavior to one implementation rather than choosing an algorithm. |
Key Takeaways
- The strategy pattern selects interchangeable algorithms behind a small stable interface.
- Keep strategies side-effect-aware and injectable so they can be independently tested.
- A decorator adds behavior to one implementation rather than choosing an algorithm.
Before adapting these examples, verify the return values, test the failure paths and confirm that your application meets its security and environment requirements.