PHP OOP structure problem, simulate multiple inher

2019-06-26 04:10发布

问题:

I have an e-shop with multiple product types. And i would have thought of the following structure

Cart_Item
-- Cart_Product
-- Cart_Download

Order_Item extends Cart_Item
-- Order_Product
-- Order_Download

The problem is that i want to have Order_Product extend Order_Item and Cart_Product. This is because it needs method generic to Order_Item ( get price from Order not from product ) but also methods from Cart_Product ( shipping calculations )

I know that php doesn't support multiple inheritance, i was wandering what is the cleanest way to emulate this.

Right now i have Order_Product extend Cart_Product duplicate code from Order_Item in Order_Product an Order_Download.

回答1:

Either use Interfaces and implement the methods manually or via Strategies. Or use Composition instead of Inheritance, meaning you let the Order_Product have a Order_Item and a Cart_Product.

On a sidenote: You could also consider making "shipping calculations" into it's own Service class that you can pass appropriate Product instances to.