【问题标题】:How to implement observation if we already used intheritance?如果我们已经使用了继承,如何实现观察?
【发布时间】:2015-07-08 21:15:05
【问题描述】:

有一个ForumThread 类:

class ForumThread extends DbTable
{
    public function insert ($threadId, $comment)
    {
        SQL INSERT INTO parent::tablename VALUES $threadId, $comment
        // email sending how?
        // putting this on a "notice-wall", how?
    }
}

其他一些功能应该在这里完成,例如电子邮件发送。我不能把它放在这里,否则我违反了 SRP。我也不能把它放到controller,因为我也想在其他地方插入帖子。我计划实现 Observed 模式,但我不能从两个类扩展。

【问题讨论】:

    标签: php observer-pattern


    【解决方案1】:

    使用观察者模式,您必须从 这个方法是为了执行相关的观察者代码。

    你可以在 insert 方法中执行类似的操作:

    $this->notify('table_insertion', $data);
    

    然后在执行通知行之前的其他地方,必须像这样注册事件:

    static::$observers['table_insertion'][] = array('class_to_call' => 'method_in_class_to_call');
    

    通知方法类似于:

    public function notify($event, $data) {
      foreach(static::$observer[$event] as $class => $method) {
        new $class->$method($data);
      }
    }
    

    希望这是有道理的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-04
      • 1970-01-01
      相关资源
      最近更新 更多