← CodeClarityLab Home
Browse by Category
+ added · updated 7d
← Back to glossary

Strategy Pattern

general PHP 5.0+ Intermediate

Also Known As

strategy policy pattern interchangeable algorithm

TL;DR

Defines a family of interchangeable algorithms behind a common interface, allowing the algorithm to be selected at runtime.

Explanation

The Strategy pattern encapsulates each algorithm in its own class implementing a common interface, making them interchangeable. The context class accepts a strategy via constructor injection and delegates behaviour to it. This eliminates switch/if-else chains that select algorithms (replacing switch smell with polymorphism), makes algorithms independently testable, and follows Open/Closed Principle — new strategies are added without modifying the context. Classic PHP examples: payment processors, sorting algorithms, and report formatters.

Common Misconception

Strategy and State patterns are interchangeable since both swap behaviour. Strategy objects are chosen by the client and remain stable. State objects transition themselves — the object changes its own behaviour based on internal state transitions without the client selecting which strategy to use.

Why It Matters

The Strategy pattern defines a family of interchangeable algorithms — swapping behaviour at runtime without conditionals, making it easy to add new strategies without modifying existing code.

Common Mistakes

  • Strategies that depend on the context object — they should be independent algorithms.
  • Too many strategies for trivial variations — a simple parameter is cleaner than a strategy class.
  • Not using interfaces for strategies — callers become coupled to concrete strategy types.
  • Forgetting to inject the strategy — instantiating it inside the context defeats the purpose.

Code Examples

✗ Vulnerable
function sortUsers(array $users, string $by): array {
    if ($by === 'name') {
        usort($users, fn($a,$b) => strcmp($a->name, $b->name));
    } elseif ($by === 'age') {
        usort($users, fn($a,$b) => $a->age <=> $b->age);
    } elseif ($by === 'score') {
        usort($users, fn($a,$b) => $b->score <=> $a->score);
    } // must edit this function for every new sort
    return $users;
}
✓ Fixed
interface SortStrategy {
    public function compare(User $a, User $b): int;
}

class SortByName  implements SortStrategy { public function compare(User $a, User $b): int { return strcmp($a->name, $b->name); } }
class SortByAge   implements SortStrategy { public function compare(User $a, User $b): int { return $a->age <=> $b->age; } }
class SortByScore implements SortStrategy { public function compare(User $a, User $b): int { return $b->score <=> $a->score; } }

function sortUsers(array $users, SortStrategy $strategy): array {
    usort($users, $strategy->compare(...));
    return $users;
}

Added 15 Mar 2026
Edited 22 Mar 2026
Views 23
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
0 pings F 0 pings S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 0 pings F 0 pings S 0 pings S 0 pings M 0 pings T 1 ping W 2 pings T 1 ping F 0 pings S 0 pings S 1 ping M 0 pings T 0 pings W 0 pings T 2 pings F 1 ping S 0 pings S 1 ping M 0 pings T 0 pings W 0 pings T 0 pings F 1 ping S
No pings yesterday
Amazonbot 6 Perplexity 5 Google 5 Unknown AI 2 Ahrefs 2 ChatGPT 2
crawler 18 crawler_json 4
DEV INTEL Tools & Severity
🟢 Low ⚙ Fix effort: Medium
⚡ Quick Fix
Extract the varying algorithm into an interface, create one class per strategy, inject the chosen strategy — eliminates the switch/if-else that changes every time a new algorithm is added
📦 Applies To
PHP 5.0+ web cli queue-worker
🔗 Prerequisites
🔍 Detection Hints
switch($algorithm) or if($type==='stripe') branching on algorithm choice in the middle of business logic
Auto-detectable: ✗ No phpstan psalm
⚠ Related Problems
🤖 AI Agent
Confidence: Low False Positives: High ✗ Manual fix Fix: Medium Context: Class Tests: Update

✓ schema.org compliant