Junior — Middle
Can you give an example of the most complex design pattern you have applied in practice?
sobes.tech AI
Answer from AI
One of the most complex design patterns I have worked with in PHP is the "State" pattern. This pattern allows an object to change its behavior depending on its internal state, without changing its class.
Example of usage: I had a project with an order system, where an order could be in different states (new, paid, shipped, canceled). Instead of many conditional operators, I implemented each state as a separate class implementing a common interface, and dynamically switched the order's state.
interface OrderState {
public function proceed(OrderContext $order);
}
class NewOrderState implements OrderState {
public function proceed(OrderContext $order) {
// logic to transition to "paid" state
$order->setState(new PaidOrderState());
}
}
class PaidOrderState implements OrderState {
public function proceed(OrderContext $order) {
// logic to transition to "shipped" state
$order->setState(new ShippedOrderState());
}
}
class OrderContext {
private $state;
public function __construct(OrderState $state) {
$this->state = $state;
}
public function setState(OrderState $state) {
$this->state = $state;
}
public function proceed() {
$this->state->proceed($this);
}
}
// Usage
$order = new OrderContext(new NewOrderState());
$order->proceed(); // transitions to PaidOrderState
$order->proceed(); // transitions to ShippedOrderState
This pattern is complex because it requires a good understanding of OOP principles and proper class design for managing states, but it significantly improves code readability and extensibility.