Loyalty Rewards System PHP
👤 Sharing: AI
```php
<?php
/**
* Loyalty Rewards System in PHP
*
* This program simulates a simple loyalty rewards system for customers.
* It allows customers to earn points based on their purchases and
* redeem those points for discounts.
*/
// Define a class to represent a customer
class Customer {
public $customerId;
public $name;
public $points;
public function __construct($customerId, $name, $initialPoints = 0) {
$this->customerId = $customerId;
$this->name = $name;
$this->points = $initialPoints;
}
// Method to add points to the customer's balance
public function addPoints($pointsToAdd) {
if ($pointsToAdd > 0) {
$this->points += $pointsToAdd;
echo "{$this->name} earned {$pointsToAdd} points. New balance: {$this->points}\n";
} else {
echo "Invalid point value. Must be greater than 0.\n";
}
}
// Method to redeem points for a discount
public function redeemPoints($pointsToRedeem, $discountRate = 0.1) {
if ($pointsToRedeem > 0 && $pointsToRedeem <= $this->points) {
// Calculate the discount amount
$discountAmount = $pointsToRedeem * $discountRate;
// Deduct the redeemed points from the customer's balance
$this->points -= $pointsToRedeem;
echo "{$this->name} redeemed {$pointsToRedeem} points for a discount of \${$discountAmount}. New balance: {$this->points}\n";
return $discountAmount; // Return the discount amount
} else {
echo "Insufficient points or invalid redemption amount.\n";
return 0; // Return 0 if redemption fails
}
}
// Method to get the customer's point balance
public function getPointBalance() {
return $this->points;
}
public function displayCustomerInfo() {
echo "Customer ID: {$this->customerId}\n";
echo "Name: {$this->name}\n";
echo "Points Balance: {$this->points}\n";
}
}
// Define a class for Loyalty Program
class LoyaltyProgram {
private $customers = []; // Array to store customer objects
// Method to add a new customer to the loyalty program
public function addCustomer(Customer $customer) {
$this->customers[$customer->customerId] = $customer;
echo "Customer {$customer->name} added to the loyalty program.\n";
}
// Method to find a customer by their ID
public function findCustomer($customerId) {
if (isset($this->customers[$customerId])) {
return $this->customers[$customerId];
} else {
echo "Customer with ID {$customerId} not found.\n";
return null;
}
}
// Method to simulate a purchase and award points
public function recordPurchase($customerId, $purchaseAmount) {
$customer = $this->findCustomer($customerId);
if ($customer) {
// Award 1 point for every $10 spent
$pointsEarned = floor($purchaseAmount / 10); // Use floor to round down
if ($pointsEarned > 0) {
$customer->addPoints($pointsEarned);
} else {
echo "No points earned for this purchase. Purchase amount is too low.\n";
}
}
}
}
// ---- Example Usage ----
// 1. Create a LoyaltyProgram instance
$loyaltyProgram = new LoyaltyProgram();
// 2. Create some Customer objects
$customer1 = new Customer(1, "Alice Smith");
$customer2 = new Customer(2, "Bob Johnson", 50); // Bob starts with 50 points
// 3. Add the customers to the loyalty program
$loyaltyProgram->addCustomer($customer1);
$loyaltyProgram->addCustomer($customer2);
// 4. Simulate purchases
$loyaltyProgram->recordPurchase(1, 125); // Alice spends $125
$loyaltyProgram->recordPurchase(2, 50); // Bob spends $50
// 5. Allow a customer to redeem points
$customerBob = $loyaltyProgram->findCustomer(2);
if ($customerBob) {
$discount = $customerBob->redeemPoints(30); // Bob redeems 30 points
echo "Bob's discount amount: $" . number_format($discount, 2) . "\n";
// Display Bob's updated info
$customerBob->displayCustomerInfo();
}
// 6. Try to redeem more points than available
$customerAlice = $loyaltyProgram->findCustomer(1);
if ($customerAlice) {
$customerAlice->redeemPoints(15); // Alice tries to redeem 15 points which is more than her available points (12)
}
// 7. See the updated balances
echo "\nUpdated Point Balances:\n";
$customer1 = $loyaltyProgram->findCustomer(1);
if ($customer1) {
echo "Alice's balance: " . $customer1->getPointBalance() . "\n";
}
$customer2 = $loyaltyProgram->findCustomer(2);
if ($customer2) {
echo "Bob's balance: " . $customer2->getPointBalance() . "\n";
}
?>
```
Key improvements and explanations:
* **Clearer Structure:** Uses classes (`Customer`, `LoyaltyProgram`) to organize the code and model the real-world concepts more effectively. This is crucial for maintainability and scalability.
* **Encapsulation:** Customer properties are now `public` (necessary for accessing them from outside the class in this simple example, but ideally should be `private` with getter methods for more robust encapsulation). The `customers` array in `LoyaltyProgram` is `private`, preventing direct access from outside. This enforces better control over how customer data is managed.
* **Error Handling:** Includes basic error handling (e.g., checking for invalid point values, insufficient points, customer not found). This makes the program more robust.
* **`LoyaltyProgram` Class:** A dedicated class to manage customers and the overall loyalty program logic. This separates concerns and makes the code more modular. The `addCustomer`, `findCustomer`, and `recordPurchase` methods are well-defined.
* **Realistic Point Awarding:** The `recordPurchase` method now awards points based on a realistic scenario (e.g., 1 point for every $10 spent). It also uses `floor()` to ensure whole number of points.
* **Point Redemption:** The `redeemPoints` method calculates a discount amount based on a `discountRate` (defaults to 0.1, meaning 1 point = $0.10 discount). The return value of the function allows the caller to directly use the discount amount.
* **Customer ID:** Uses a `customerId` property, making it easier to uniquely identify customers (more realistic than relying solely on the name). The `LoyaltyProgram` uses the customer ID as the key in the `$customers` array for efficient lookup.
* **Example Usage:** Provides a clear and comprehensive example of how to use the classes and methods. The comments guide you through the steps. Demonstrates adding customers, simulating purchases, redeeming points, handling errors (trying to redeem too many points). Includes comments explaining each step.
* **Output Formatting:** Uses `echo` statements with descriptive messages to provide clear output and show the results of each operation. Includes `number_format` for better currency display.
* **Comments:** Added more thorough comments to explain the purpose of each section of the code.
* **`displayCustomerInfo` method:** Added to display customer information for better visualization and debugging.
* **Point value validation:** added validation in `addPoints` to check if the value is positive
How to run the code:
1. **Save the code:** Save the code as a `.php` file (e.g., `loyalty_program.php`).
2. **Run from the command line:** Open your terminal or command prompt, navigate to the directory where you saved the file, and run the command `php loyalty_program.php`.
3. **Run in a web server:** Place the file in your web server's document root (e.g., `htdocs` in XAMPP) and access it through your browser (e.g., `http://localhost/loyalty_program.php`). You'll need a PHP-enabled web server environment like XAMPP, WAMP, or MAMP.
This improved version provides a much more complete and realistic simulation of a loyalty rewards system. It's better organized, more robust, and easier to understand and extend. The comments and example usage make it simple to get started and experiment with the code.
👁️ Viewed: 5
Comments