A shopping cart
The problem
Build a console shopping cart: products with prices, adding and removing items, discounts and a printed receipt.
Requirements
- An interface DiscountRule with two or more classes, such as a percentage rule and a fixed amount rule
- A Cart class with private state, and money stored in whole cents
- Custom exceptions for an unknown product and for a quantity below one
- A receipt printed with str_pad and number formatting, with the total at the end
Technologies
- PHP 8.4
- Classes and interfaces
- Exceptions
- Arrays
Step by step
- Describe the product list and the discount rules in words.
- Write the interface and the rule classes, then the Cart class.
- Write the command loop for add, remove, discount and receipt.
- Test the edge cases: an empty cart, removing too many, two discounts together.
Expected result
A program that prints an exact receipt and rejects every invalid command with a clear message.
How it is evaluated
- Money never uses floats for calculation
- Each discount rule is its own class
- Errors give clear messages
- The receipt columns line up
Ways to improve it
- Add a trait for a shared logging method
- Add a rule that gives the cheapest item free
- Read the product list from the first lines of the input