Bird
Raised Fist0
PHPprogramming~5 mins

Strategy pattern in PHP - Cheat Sheet & Quick Revision

Choose your learning style10 modes available
Recall & Review
beginner
What is the Strategy pattern?
The Strategy pattern is a design pattern that lets you choose an algorithm's behavior at runtime. It defines a family of algorithms, puts each one in a separate class, and makes their objects interchangeable.
Click to reveal answer
beginner
How does the Strategy pattern help in programming?
It helps by separating the algorithm from the code that uses it. This makes the code easier to change and extend without modifying existing code.
Click to reveal answer
intermediate
In PHP, how do you implement the Strategy pattern?
You create an interface for the strategy, then create classes that implement this interface for each algorithm. The context class holds a reference to a strategy object and delegates work to it.
Click to reveal answer
intermediate
What is the role of the Context class in the Strategy pattern?
The Context class uses a Strategy object to execute the algorithm. It does not know the details of the algorithm, only that it can call a method on the strategy.
Click to reveal answer
beginner
Give a simple real-life example of the Strategy pattern.
Choosing a payment method in an online store is like the Strategy pattern. You can pay by credit card, PayPal, or bank transfer. Each payment method is a strategy, and the store uses the chosen one to process payment.
Click to reveal answer
What does the Strategy pattern allow you to do?
ACreate multiple unrelated classes
BChange the algorithm used at runtime
CWrite code without any classes
DAvoid using interfaces
In the Strategy pattern, what does the Context class do?
AHolds a reference to a strategy and uses it
BImplements all algorithms
CDefines the interface for strategies
DCreates new strategies dynamically
Which PHP feature is commonly used to define strategies?
AInterfaces
BTraits
CAbstract classes only
DGlobal functions
Why is the Strategy pattern useful?
AIt makes code run faster
BIt forces all algorithms to be in one class
CIt removes the need for classes
DIt reduces code duplication and increases flexibility
Which of these is NOT a benefit of the Strategy pattern?
AEasier to add new algorithms
BBetter separation of concerns
CHarder to test individual algorithms
DAbility to change behavior at runtime
Explain the Strategy pattern and how it separates concerns in code.
Think about how you can swap different ways to do something without changing the main code.
You got /4 concepts.
    Describe a simple PHP example using the Strategy pattern for different sorting algorithms.
    Imagine you want to sort data but want to pick the method later.
    You got /4 concepts.

      Practice

      (1/5)
      1.

      What is the main purpose of the Strategy pattern in PHP?

      easy
      A. To allow changing the algorithm or behavior at runtime without modifying the context.
      B. To create multiple instances of the same class.
      C. To store data in a database efficiently.
      D. To handle errors and exceptions in the code.

      Solution

      1. Step 1: Understand the Strategy pattern concept

        The Strategy pattern is designed to let you swap different algorithms or behaviors easily without changing the main code that uses them.
      2. Step 2: Identify the correct purpose

        Among the options, only To allow changing the algorithm or behavior at runtime without modifying the context. describes this behavior: changing the algorithm at runtime without modifying the context class.
      3. Final Answer:

        To allow changing the algorithm or behavior at runtime without modifying the context. -> Option A
      4. Quick Check:

        Strategy pattern = change behavior easily [OK]
      Hint: Strategy pattern swaps algorithms without changing main code [OK]
      Common Mistakes:
      • Confusing Strategy with Singleton or Factory patterns
      • Thinking it manages data storage
      • Assuming it handles errors
      2.

      Which of the following is the correct way to define a strategy interface in PHP?

      ?
      easy
      A. interface Strategy { function execute() {} }
      B. class Strategy { function execute() {} }
      C. interface Strategy { public function execute(); }
      D. abstract class Strategy { public execute(); }

      Solution

      1. Step 1: Recall PHP interface syntax

        In PHP, interfaces are declared with the keyword interface, and methods inside must be declared without a body and with visibility (usually public).
      2. Step 2: Check each option

        interface Strategy { public function execute(); } correctly declares an interface with a public method without a body. class Strategy { function execute() {} } uses a class, not interface. interface Strategy { function execute() {} } incorrectly provides a method body inside interface. abstract class Strategy { public execute(); } uses abstract class but misses parentheses and visibility.
      3. Final Answer:

        interface Strategy { public function execute(); } -> Option C
      4. Quick Check:

        Interface method = declaration only [OK]
      Hint: Interface methods have no body, use 'public function name();' [OK]
      Common Mistakes:
      • Adding method body inside interface
      • Using class instead of interface
      • Omitting visibility keyword
      3.

      What will be the output of the following PHP code using the Strategy pattern?

      interface Strategy {
          public function execute();
      }
      
      class AddStrategy implements Strategy {
          public function execute() {
              return 5 + 3;
          }
      }
      
      class MultiplyStrategy implements Strategy {
          public function execute() {
              return 5 * 3;
          }
      }
      
      class Context {
          private Strategy $strategy;
          public function __construct(Strategy $strategy) {
              $this->strategy = $strategy;
          }
          public function executeStrategy() {
              return $this->strategy->execute();
          }
      }
      
      $context = new Context(new MultiplyStrategy());
      echo $context->executeStrategy();
      
      medium
      A. 8
      B. 15
      C. 53
      D. Error: Cannot instantiate interface

      Solution

      1. Step 1: Understand the code flow

        The code defines two strategies: AddStrategy returns 5+3=8, MultiplyStrategy returns 5*3=15. The Context class uses the strategy passed in constructor.
      2. Step 2: Identify which strategy is used

        The context is created with new MultiplyStrategy(), so calling executeStrategy() returns 15.
      3. Final Answer:

        15 -> Option B
      4. Quick Check:

        MultiplyStrategy returns 15 [OK]
      Hint: Check which strategy object is passed to context [OK]
      Common Mistakes:
      • Confusing AddStrategy and MultiplyStrategy output
      • Thinking interface cannot be instantiated (only concrete classes)
      • Ignoring which strategy is passed
      4.

      Identify the error in the following PHP code implementing the Strategy pattern:

      interface Strategy {
          public function execute();
      }
      
      class ConcreteStrategy implements Strategy {
          public function execute() {
              echo "Running strategy";
          }
      }
      
      class Context {
          private $strategy;
          public function __construct(Strategy $strategy) {
              $this->strategy = $strategy;
          }
          public function executeStrategy() {
              $this->strategy->execute;
          }
      }
      
      $context = new Context(new ConcreteStrategy());
      $context->executeStrategy();
      
      medium
      A. Cannot instantiate interface directly
      B. Strategy interface missing method body
      C. Context constructor missing type hint
      D. Missing parentheses when calling execute method

      Solution

      1. Step 1: Check method call syntax in Context

        Inside executeStrategy(), the code calls $this->strategy->execute; without parentheses, so the method is not actually called.
      2. Step 2: Identify correct fix

        Method calls require parentheses even if no arguments: $this->strategy->execute();.
      3. Final Answer:

        Missing parentheses when calling execute method -> Option D
      4. Quick Check:

        Method call needs () [OK]
      Hint: Always use () to call methods in PHP [OK]
      Common Mistakes:
      • Forgetting parentheses on method calls
      • Confusing interface method declaration with implementation
      • Ignoring type hints in constructor
      5.

      You want to add a new strategy SubtractStrategy to the existing PHP Strategy pattern code. Which of the following is the best way to implement it?

      interface Strategy {
          public function execute(int $a, int $b): int;
      }
      
      class AddStrategy implements Strategy {
          public function execute(int $a, int $b): int {
              return $a + $b;
          }
      }
      
      // Your code here
      
      hard
      A. class SubtractStrategy implements Strategy { public function execute(int $a, int $b): int { return $a - $b; } }
      B. class SubtractStrategy { public function execute(int $a, int $b): int { return $a - $b; } }
      C. class SubtractStrategy implements Strategy { public function execute(int $a, int $b) { return $a - $b; } }
      D. class SubtractStrategy implements Strategy { public function execute($a, $b): int { return $a - $b; } }

      Solution

      1. Step 1: Check interface method signature

        The interface requires execute(int $a, int $b): int with type hints and return type.
      2. Step 2: Match method signature exactly in SubtractStrategy

        class SubtractStrategy implements Strategy { public function execute(int $a, int $b): int { return $a - $b; } } matches the interface exactly with parameter types and return type. class SubtractStrategy { public function execute(int $a, int $b): int { return $a - $b; } } misses implementing the interface. class SubtractStrategy implements Strategy { public function execute(int $a, int $b) { return $a - $b; } } misses return type. class SubtractStrategy implements Strategy { public function execute($a, $b): int { return $a - $b; } } misses parameter types.
      3. Final Answer:

        class SubtractStrategy implements Strategy { public function execute(int $a, int $b): int { return $a - $b; } } -> Option A
      4. Quick Check:

        Implement interface with exact method signature [OK]
      Hint: Match interface method signature exactly when implementing [OK]
      Common Mistakes:
      • Omitting interface implementation
      • Missing type hints or return types
      • Changing method signature
      Recommended

      Ready to prove it?

      Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

      10 questions~5 mineasy hard