Junior — Middle
How to implement a method for calculating discounts based on a specific user?
sobes.tech AI
Answer from AI
To choose a discount calculation method depending on a specific user in PHP, you can use the "Strategy" pattern. The idea is to define different discount calculation classes and select the appropriate one based on the user's properties.
Example:
interface DiscountStrategy {
public function calculate(float $price): float;
}
class VipDiscount implements DiscountStrategy {
public function calculate(float $price): float {
return $price * 0.8; // 20% discount
}
}
class RegularDiscount implements DiscountStrategy {
public function calculate(float $price): float {
return $price * 0.95; // 5% discount
}
}
class NoDiscount implements DiscountStrategy {
public function calculate(float $price): float {
return $price; // no discount
}
}
class User {
public string $type; // e.g., 'vip', 'regular', 'guest'
public function __construct(string $type) {
$this->type = $type;
}
}
function getDiscountStrategy(User $user): DiscountStrategy {
switch ($user->type) {
case 'vip':
return new VipDiscount();
case 'regular':
return new RegularDiscount();
default:
return new NoDiscount();
}
}
// Usage
$user = new User('vip');
$strategy = getDiscountStrategy($user);
$finalPrice = $strategy->calculate(1000);
echo $finalPrice; // 800
This approach allows easy extension of discount logic and maintenance of the code.