The Strategy Pattern is a behavioral design pattern that allows dynamic selection of algorithms at runtime. In PHP, using the Strategy Pattern helps decouple logic, making the codebase more flexible and maintainable. It follows the Open/Closed Principle—open for extension, closed for modification.
Consider an e-commerce scenario where different user tiers get different discounts: regular users pay full price, VIP users get a 10% discount, and SVIP users receive a 20% discount. By using the Strategy Pattern, we can encapsulate each pricing strategy into its own class for better organization and extensibility.
abstract class PriceStrategy {
abstract public function calculatePrice($price);
}
For each user tier, we implement a class that extends PriceStrategy:
class RegularStrategy extends PriceStrategy {
public function calculatePrice($price) {
return $price;
}
}
class VipStrategy extends PriceStrategy {
public function calculatePrice($price) {
return $price * 0.9;
}
}
class SvipStrategy extends PriceStrategy {
public function calculatePrice($price) {
return $price * 0.8;
}
}
The Order class uses a strategy instance to perform price calculation:
class Order {
private $priceStrategy;
public function setPriceStrategy(PriceStrategy $strategy) {
$this->priceStrategy = $strategy;
}
public function calculateTotalPrice($price) {
return $this->priceStrategy->calculatePrice($price);
}
}
Here’s how to use the strategy pattern to compute prices based on user type:
$order = new Order();
$regularStrategy = new RegularStrategy();
$order->setPriceStrategy($regularStrategy);
$regularPrice = $order->calculateTotalPrice(100); // Outputs 100
$vipStrategy = new VipStrategy();
$order->setPriceStrategy($vipStrategy);
$vipPrice = $order->calculateTotalPrice(100); // Outputs 90
$svipStrategy = new SvipStrategy();
$order->setPriceStrategy($svipStrategy);
$svipPrice = $order->calculateTotalPrice(100); // Outputs 80
With the Strategy Pattern, each business rule is encapsulated in its own class, leading to cleaner, more modular code. It’s easy to add new strategies without modifying existing code, making the system easier to maintain and scale.
The Strategy Pattern is a highly useful design pattern in PHP object-oriented development. It simplifies handling varying behaviors and keeps logic clean and organized. Applying this pattern effectively improves code readability, maintainability, and scalability in real-world projects.