0
0
PHPprogramming~10 mins

Strategy pattern in PHP - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Strategy pattern
Client code
Choose strategy
Set strategy object
Call strategy method
Strategy executes algorithm
Return result to client
The client picks a strategy object, sets it, then calls its method to run the chosen algorithm.
Execution Sample
PHP
<?php
interface Strategy {
  public function doOperation(int $a, int $b): int;
}

class AddStrategy implements Strategy {
  public function doOperation(int $a, int $b): int {
    return $a + $b;
  }
}

class Context {
  private Strategy $strategy;
  public function __construct(Strategy $strategy) {
    $this->strategy = $strategy;
  }
  public function executeStrategy(int $a, int $b): int {
    return $this->strategy->doOperation($a, $b);
  }
}

$addStrategy = new AddStrategy();
$context = new Context($addStrategy);
echo $context->executeStrategy(5, 3); // Outputs 8
?>
This code uses the Strategy pattern to add two numbers by choosing the AddStrategy.
Execution Table
StepActionObject/VariableValue/ResultExplanation
1Create AddStrategy object$addStrategyAddStrategy instanceAddStrategy object created to perform addition
2Create Context with AddStrategy$contextContext instance with AddStrategyContext stores the strategy object
3Call executeStrategy(5, 3)executeStrategyCalls AddStrategy->doOperation(5,3)Context delegates operation to strategy
4AddStrategy->doOperation(5,3)doOperation8AddStrategy adds 5 + 3 and returns 8
5executeStrategy returnsexecuteStrategy8Context returns the result from strategy
6echo outputOutput8Program prints 8 to the screen
💡 Execution ends after printing the result 8
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4Final
$addStrategynullAddStrategy instanceAddStrategy instanceAddStrategy instanceAddStrategy instanceAddStrategy instance
$contextnullnullContext instance with AddStrategyContext instance with AddStrategyContext instance with AddStrategyContext instance with AddStrategy
Resultnullnullnullnull88
Key Moments - 3 Insights
Why does the Context class need a Strategy object?
The Context holds a Strategy object to delegate the operation. As shown in step 2 and 3 of the execution_table, Context calls the strategy's method to perform the algorithm.
How does the program decide which algorithm to run?
The program decides by which Strategy object is passed to Context. In step 1, AddStrategy is created and passed to Context in step 2, so addition is performed.
What if we want to change the operation at runtime?
We can create a new Strategy object and set it in Context. This flexibility is the main benefit of the Strategy pattern, allowing different algorithms without changing Context.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value returned by AddStrategy->doOperation at step 4?
A3
B5
C8
Dnull
💡 Hint
Check the 'Value/Result' column in row for step 4 in execution_table
At which step does the Context object get created with the strategy?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the 'Action' and 'Object/Variable' columns in execution_table for when Context is created
If we replaced AddStrategy with a MultiplyStrategy, what would change in the execution_table?
AStep 4 result would be multiplication of inputs
BStep 2 would not create Context
CStep 6 would print null
DNo change at all
💡 Hint
Focus on step 4 where the strategy's operation result is shown
Concept Snapshot
Strategy pattern lets you choose an algorithm at runtime.
Define a Strategy interface with a method.
Create concrete Strategy classes implementing the interface.
Context holds a Strategy object and calls its method.
Change strategy to change behavior without changing Context.
Full Transcript
The Strategy pattern helps us pick different ways to do a task without changing the main code. We create a Strategy interface with a method for the task. Then, we make classes that do the task differently. The Context class holds one of these strategy objects and calls its method to run the chosen algorithm. In the example, AddStrategy adds two numbers. The Context uses AddStrategy to add 5 and 3, returning 8. This way, we can swap strategies anytime to change behavior easily.