PHP中的多重继承

PHP中的多重继承,第1张

PHP中的多重继承

Alex,大多数时候,您需要多重继承是一个信号,表明您的对象结构有些不正确。在您概述的情况下,我看到您的班级职责范围太广。如果Message是应用程序业务模型的一部分,则不应考虑呈现输出。相反,您可以划分责任并使用MessageDispatcher来发送使用文本或html后端传递的消息。我不知道您的代码,但是让我这样模拟:

$m = new Message();$m->type = 'text/html';$m->from = 'John Doe <[email protected]>';$m->to = 'Random Hacker <[email protected]>';$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);

请注意,MessageDispatcher将根据

type
传递的Message对象中的属性来决定是以HTML还是纯文本形式发送。

// in MessageDispatcher classpublic 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类中完成,并将发送算法委托给调度程序。这称为策略模式,您可以在此处阅读更多内容。



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5476155.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-12
下一篇 2022-12-12

发表评论

登录后才能评论

评论列表(0条)

保存