0
0
PHPprogramming~10 mins

Strategy pattern in PHP - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare the Strategy interface.

PHP
<?php
interface [1] {
    public function execute();
}
?>
Drag options to blanks, or click blank then click option'
AStrategy
BContext
CAlgorithm
DExecutor
Attempts:
3 left
💡 Hint
Common Mistakes
Using a class name instead of interface.
Naming the interface 'Context' or other unrelated names.
2fill in blank
medium

Complete the code to implement a concrete strategy class.

PHP
<?php
class ConcreteStrategyA implements [1] {
    public function execute() {
        echo "Strategy A executed.";
    }
}
?>
Drag options to blanks, or click blank then click option'
AStrategy
BExecutor
CContext
DAlgorithm
Attempts:
3 left
💡 Hint
Common Mistakes
Implementing a class instead of an interface.
Using wrong interface name.
3fill in blank
hard

Fix the error in the Context class constructor to accept a strategy.

PHP
<?php
class Context {
    private $strategy;

    public function __construct([1] $strategy) {
        $this->strategy = $strategy;
    }
}
?>
Drag options to blanks, or click blank then click option'
AConcreteStrategyA
BExecutor
CContext
DStrategy
Attempts:
3 left
💡 Hint
Common Mistakes
Using a concrete class type hint instead of the interface.
Using the class name 'Context' as type hint.
4fill in blank
hard

Complete the code to call the strategy's execute method inside Context.

PHP
<?php
class Context {
    private $strategy;

    public function __construct(Strategy $strategy) {
        $this->strategy = $strategy;
    }

    public function executeStrategy() {
        $this->strategy->execute[1];
    }
}
?>
Drag options to blanks, or click blank then click option'
A->
B()
C.
D;
Attempts:
3 left
💡 Hint
Common Mistakes
Using dot operator instead of ->.
Forgetting parentheses when calling the method.
5fill in blank
hard

Fill all three blanks to create a Context with a ConcreteStrategyA and execute it.

PHP
<?php
$strategy = new [1]();
$context = new Context([2]);
$context->[3]();
?>
Drag options to blanks, or click blank then click option'
AConcreteStrategyA
B$strategy
CexecuteStrategy
DStrategy
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the class name instead of the object to Context.
Calling a non-existent method on Context.