I have reading about SOLID principles last week and decided to try to solve real world problem by using them. So I got the problem of real world ecommerce site managing totals.
Problem Statement: We have to calculate some totals like subtotal, taxes, vouchers, coupon, total on a cart products.
So I have decided to make TotalManager which returns total_data and total to the rest of the program.
// total data variable looks like
array('key'=>value)
e.g. array('subtotal'=>100,'total'=>150,'tax'=>50)
class TotalManager{
private $total_data;
public function get_total_data()
{
$totals = array('subtotal','total','taxes')
// foreach totals array gets each object check its instance of interface itotal and called it's get method.
}
}
Interface Itotal
{
public function get_total_data();
public function get_total();
}
class subtotal implements Itotal
{
public function get_total_data()
{
// it needs cart object
// get the cart product calculate totals and return total_data and total
}
public function get_total()
{
return the subtotal in double/float
}
}
class total implements Itotal
{
public function get_total_data()
{
// get the other totals object and calls it get_total method
// calulate sum of all totals and return
}
public function get_total()
{
// calculate total and return back;
}
}
But I am facing problems in this model:
For dependency inversion principle I cannot directly create the object of cart or subtotal in subtotal, Total class respectively I have to pass them from controller at total manager.
When I think about that whenever I am adding the class I have to change the Total manager for adding the new method so it's violating open/closed principle. How to solve this in OOD?