PHP OOP结构问题,模拟多重继承

发布于 2024-09-26 19:07:08 字数 439 浏览 0 评论 0原文

我有一个有多种产品类型的电子商店。我会想到以下结构

Cart_Item
-- Cart_Product
-- Cart_Download

Order_Item extends Cart_Item
-- Order_Product
-- Order_Download

问题是我想让 Order_Product 扩展 Order_Item 和 Cart_Product。 这是因为它需要 Order_Item 的通用方法(从 Order 而不是从产品获取价格),而且还需要 Cart_Product 的方法(运输计算)

我知道 php 不支持多重继承,我在想什么是模拟这个的最干净的方法。

现在我有 Order_Product 从 Order_Product 和 Order_Download 中的 Order_Item 扩展了 Cart_Product 重复代码。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

人疚 2024-10-03 19:07:08

使用 接口 并手动或通过 策略。或者使用 组合 而不是继承,这意味着您让 Order_Product 有一个 Order_Item 和一个 Cart_Product

旁注:您还可以考虑将“运费计算”放入其自己的服务类中,您可以将适当的产品实例传递给该服务类。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文