子类实现接口可以吗?
我正在尝试更严肃的 OOP(以前只是使用继承),并且偶然发现了一些让我困惑的东西。
我有一个处理数据库连接的超类。
我有一个子类,用于处理与站点成员资格功能相关的连接,
我想采用策略模式来允许不同但相似的功能共存。例如:
- 连接数据库并检查名称 和用于新注册的电子邮件
- 连接到数据库并检查用户名和确认码以进行注册确认
- 连接到数据库并检查用于登录的用户名和密码
I am dipping my toes in more serious OOP (previously, just used inheritance) and I have stumbled across something that has confused me.
I have a super class that handles my database connection.
I have a subclass that handles connections related to a site's membership functions
I would like to employ the strategy pattern to allow different but similar functions to coexist. For example:
- connect to database and check name
and email for new registrations - connection to database and check username and confirmation code for registration confirmation
- connect to database and check username and password for login
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
答案
是
:是的,抽象类可以扩展 PHP 中的超类。
标题更新后编辑:
是的,子类实现接口是完全可以的。但是,在策略的上下文中,除了捕获抽象并将实现细节隐藏在派生类中的接口之外,您可能不会调用任何其他接口上的方法。请参阅http://sourcemaking.com/design_patterns/strategy
This
gives
so the answer is: Yes, an abstract class can extend a super class in PHP.
EDIT after title update:
Yes, it is perfectly fine for a subclass to implement an interface. However, in the context of a Strategy you will likely not call the methods on any other interface than the interface that captures the abstraction and buries implementation details in derived classes. See http://sourcemaking.com/design_patterns/strategy
如果不知道你的代码,这个问题很难回答。根据我从你的问题中得出的结论,我想说在这种情况下你应该使用组合而不是继承。
您可以拥有各种包含数据库连接的“服务类”,以进行与特定问题域相关的查询。它们都有一个可用于进行查询的属性
$dbConnection
。您可以使用依赖项注入从外部设置该属性,可以使用 setter 方法 (setDbConnection($dbConnection)
),也可以直接在各种服务对象的构造函数中将其传递到参数中。Without knowing your code, this is difficult to answer. From what I can derive from your question, I would say in this case you should use composition instead of inheritance.
You could have various "service classes" that incorporate the database connection to make queries relating to a specific problem domain. They all have a property
$dbConnection
they can use to make the queries. You set that property from outside using dependency injection, either with a setter method (setDbConnection($dbConnection)
) or by passing it in a parameter directly in the constructor of the various service objects.