在php中模拟多重继承

发布于 2024-08-09 02:23:49 字数 911 浏览 2 评论 0原文

我有一个模型系统:

abstract class R00_Model_iUnique { }
abstract class R00_Model_iFamilyUnique extends R00_Model_iUnique { } // for models with hierarchy
abstract class R00_Model_iTaggedUnique extends R00_Model_iUnique { } // for models with tags

// and, for example
class R00_Model_User extends R00_Model_iUnique { }
class R00_Model_Comment extends R00_Model_iFamilyUnique { }
class R00_Model_Post extends R00_Model_iTaggedUnique { }

将会有 R00_Model_iCommentableUnique 和 R00_Model_Post 希望从中继承。但这是不可能的,它已经继承自 R00_Model_iTaggedUnique,而且我认为从 R00_Model_iCommentableUnique 继承 R00_Model_iTaggedUnique 并不明智,反之亦然。我只想到了一个如何实现它的想法,但我有一些疑问。也许你可以告诉我一些聪明的方法或批评该方法?


我想到让 R00_Model_i*Unique 不是类,而是接口,并创建辅助对象,例如 R00_Model_Helper_iUnique (也许这是一个常见的模式,并且有一个很酷的名字,我不认为“Helper”在那里会很酷? )。然后,在 R00_Model_iUnique 中,创建 __call(),它检查被调用对象的所有接口,并在帮助器中查找被调用方法。

或者有太多的反射和其他邪恶的缓慢的东西,不是吗?

I have a system of Models:

abstract class R00_Model_iUnique { }
abstract class R00_Model_iFamilyUnique extends R00_Model_iUnique { } // for models with hierarchy
abstract class R00_Model_iTaggedUnique extends R00_Model_iUnique { } // for models with tags

// and, for example
class R00_Model_User extends R00_Model_iUnique { }
class R00_Model_Comment extends R00_Model_iFamilyUnique { }
class R00_Model_Post extends R00_Model_iTaggedUnique { }

There is gonna be R00_Model_iCommentableUnique and R00_Model_Post wants to be inherited from it. But It isn't possible, it's already inherited from R00_Model_iTaggedUnique, and I don't think It's clever to inherit R00_Model_iTaggedUnique from R00_Model_iCommentableUnique or vice versa. I've thought up only one idea how to implement it, but I have some doubts. Maybe you can tell me about some smart methods or criticize that method?


I thought up to make R00_Model_i*Unique not classes, but interfaces, and create helper objects, such as R00_Model_Helper_iUnique (maybe it is a common patern, and there is a cool name, I don't think 'Helper' will be cool there?). Then, in R00_Model_iUnique, create __call(), which checks all the Interfaces of a called object and looks up a called method in the helper.

Or there is too many reflection and other evil slow stuff, isn't it?

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

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

发布评论

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

评论(1

情徒 2024-08-16 02:23:49

使用界面和助手(组合),您的方向是正确的。

这正是设计模式书(GoF)的原则之一是“优先考虑组合而不是继承”的原因之一。

组合将为您提供使用不同类的方法所需的灵活性
在你需要的班级里。

You are in the right direction with using an interface and helpers (composition).

This is precisely one of the reasons why on of the principles of the Design Patterns Book (GoF) is "Favor composition over inheritance".

Composition will give you the flexibility you require to use methods of different classes
In the class that you need it.

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