【发布时间】:2014-09-16 02:22:22
【问题描述】:
我经常遇到似乎可以通过这种方式解决的问题 - 我将给出一个具体的虚构示例,但 我想知道名称、最佳实践 - 以及这种模式是否好用总体思路。
问题
我需要将任意事件通知订阅用户。假设其中一个流程评估“订单”并且用户订阅该事件但只订阅一种类型的订单。
溶液的使用
我想代码应该是这样的:
<?php
// ...
public function processOrders() {
// ...
(new notifications\orders())->send( $typeOfOrderThatWasJustProcessed );
// ...
}
实施
所以我创建了基础通知类:
<?php
abstract class notifications {
abstract public function configurationForm();
abstract public function send();
}
以及这个特定用例的子类(语法无效,抽象方法签名与基类不同,请耐心等待):
namespace notifications;
class orders extends \notifications {
public function configurationForm() {
// prepare and return a form that will be rendered to HTML
// where the user chooses type of order that he is interested in
}
abstract public function send($type) {
// fetches needed users using the configuration which
// was provided via the form above
}
}
因此,每种类型的通知都必须具有任意参数。它们通知通知对象有关已处理的实体 - 以便通知代码可以决定自己将电子邮件发送给谁。
将本例中的 $type 视为动态值 - 可以通过数据库添加任意数量的类型。
如前所述,这对于 PHP 中的 abstract 类甚至是不可能的,我应该怎么看?
【问题讨论】:
标签: php inheritance design-patterns abstract-class