How can the State Pattern be effectively implemented in PHP to avoid using multiple switch cases?
Using the State Pattern in PHP can help avoid using multiple switch cases by encapsulating the behavior of an object into separate state classes. Each state class represents a specific behavior or state of the object, and the object delegates its behavior to the current state class. This approach promotes better code organization, extensibility, and maintainability.
<?php
interface State {
public function handleRequest();
}
class StateA implements State {
public function handleRequest() {
echo "Handling request in State A\n";
}
}
class StateB implements State {
public function handleRequest() {
echo "Handling request in State B\n";
}
}
class Context {
private $state;
public function setState(State $state) {
$this->state = $state;
}
public function request() {
$this->state->handleRequest();
}
}
$context = new Context();
$stateA = new StateA();
$stateB = new StateB();
$context->setState($stateA);
$context->request();
$context->setState($stateB);
$context->request();
?>