让我们想象一下我们的论坛系统,我想发表评论
class Thread
{
public function post ($userId, $threadId, $comment)
{
SQL INSERT INTO table $userId, $threadId, $comment
// sending emails
// public on a notice-wall
}
}
我不想要对sending emails
和public on a notice-wall
代码进行硬编码,因为即使它只是两个方法调用,它也会损害SRP原则。我可以看到两种方式:
使用助手:
public function post ($userId, $threadId, $comment)
{
SQL INSERT INTO table $userId, $threadId, $comment
ForumHelper::sendEmailsAndPublicOnNoticeWall ($userId, $threadId, $comment);
}
但是他们说这是不良做法的表现。 2,我可以使用观察者模式。那么用什么?
答案 0 :(得分:1)
class Thread
{
// ideally make this protected and use setters / getters,
// you could also consider to use an array of listeners
// to have multiple listeners
public $listener = NULL;
public function postComment($userId, $threadId, $comment)
{
// SQL INSERT INTO table $userId, $threadId, $comment
// let's assume that you have a $post object with the
// informations regarding your post
$this->_notifyOfCommentPost($postedComment);
}
protected function _notifyOfCommentPost($postedComment) {
if (!isset($this->listener)) {
return;
}
$this->listener->onPostCommented($postedComment);
}
}
此结构使您可以定义侦听器:
class OnCommentPostedListener {
public function onCommentPosted($postedComment) {
ForumHelper::sendEmailsForComment($postedComment);
ForumHelper::sendPublicOnNoticeWallForComment($postedComment);
}
}
$thread->listener = new OnCommentPostedListener();
此处发布评论时要执行的操作的行为不在管理线程的Thread类中。您的模型(如何存储信息)不了解您的业务逻辑(发送电子邮件和发布通知),它只是在执行操作时通知外部世界(可观察模式)。
这样做的好处是在发布新评论后添加新行为不需要更改Thread类。