【问题标题】:Observer pattern or helper class? (php)观察者模式还是助手类? (php)
【发布时间】:2015-07-09 09:01:27
【问题描述】:

让我们想象一下我们的论坛系统,我想发表评论

class Thread
{
    public function post ($userId, $threadId, $comment)
    {
        SQL INSERT INTO table $userId, $threadId, $comment
        // sending emails
        // public on a notice-wall
    }
}

我不想硬编码sending emailspublic on a notice-wall 代码,因为即使它只是两个方法调用,也有损SRP 原则。我可以看到两种方式:

使用助手:

public function post ($userId, $threadId, $comment)
{
    SQL INSERT INTO table $userId, $threadId, $comment
    ForumHelper::sendEmailsAndPublicOnNoticeWall ($userId, $threadId, $comment);
}

但他们说这是不良做法的标志。 第二,我可以使用观察者模式。那用什么?

【问题讨论】:

  • 您已经通过将 SRP 绑定到特定于存储的内容(即 SQL)来破坏伪代码中的 SRP。如果存储发生变化怎么办?或者如果它的版本/格式发生变化?这必须是数据映射模型层的工作。关于问题 - 使用一系列处理,您将在其中注册为您的方法执行所需的任何操作。然后您将能够对其进行配置并将实体逻辑与事件处理逻辑隔离 + 同时避免不明显的“触发”内容(想象一下 - 如果您在“观察”中有 10 多个事件 - 得到什么是多么痛苦发生在那个魔法中)

标签: php observer-pattern


【解决方案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 类。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-20
    • 2023-04-10
    • 1970-01-01
    相关资源
    最近更新 更多