如果我们已经使用了继承,如何实现观察?
How to implement observation if we already used intheritance?
有个ForumThread
class:
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
中,因为我也想在其他地方插入 post。我打算实施 Observed 模式,但我无法从两个 classes.
扩展
使用观察者模式,您必须从
这个方法是为了执行相关的观察者代码。
您可以在插入方法中执行类似这样的操作:
$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);
}
}
希望这是有道理的。
有个ForumThread
class:
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
中,因为我也想在其他地方插入 post。我打算实施 Observed 模式,但我无法从两个 classes.
使用观察者模式,您必须从 这个方法是为了执行相关的观察者代码。
您可以在插入方法中执行类似这样的操作:
$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);
}
}
希望这是有道理的。