亚历克斯,大多数时候你需要多重继承是一个信号,你的对象结构有些不正确。在您概述的情况下,我认为您的班级责任过于广泛。如果消息是应用程序业务模型的一部分,它不应该关心渲染输出。相反,您可以分担责任并使用 MessageDispatcher 发送使用文本或 html 后端传递的消息。我不知道你的代码,但让我这样模拟它:
$m = new Message();
$m->type = 'text/html';
$m->from = 'John Doe <jdoe@yahoo.com>';
$m->to = 'Random Hacker <rh@gmail.com>';
$m->subject = 'Invitation email';
$m->importBody('invitation.html');
$d = new MessageDispatcher();
$d->dispatch($m);
通过这种方式,您可以为 Message 类添加一些专业化:
$htmlIM = new InvitationHTMLMessage(); // html type, subject and body configuration in constructor
$textIM = new InvitationTextMessage(); // text type, subject and body configuration in constructor
$d = new MessageDispatcher();
$d->dispatch($htmlIM);
$d->dispatch($textIM);
type
请注意,MessageDispatcher 将根据传递的 Message 对象中的属性来决定是作为 HTML 还是纯文本发送。
// in MessageDispatcher class
public function dispatch(Message $m) {
if ($m->type == 'text/plain') {
$this->sendAsText($m);
} elseif ($m->type == 'text/html') {
$this->sendAsHTML($m);
} else {
throw new Exception("MIME type {$m->type} not supported");
}
}
总而言之,责任分为两个类。消息配置在 InvitationHTMLMessage/InvitationTextMessage 类中完成,发送算法委托给 Dispatcher。这称为策略模式,您可以在此处阅读更多信息。