【发布时间】:2011-08-10 18:20:36
【问题描述】:
我有一个网站要转换为 Codeigniter,我想简化和解耦。我喜欢我所读到的关于观察者模式的内容,例如“创建新调查”(触发新的帮助票证、触发电子邮件等)。
但是我如何在 Code Igniter 中实现这样的事情呢?我看到了 Symfony 组件,但此时我并不关心理解系统,而是关心如何在控制器和模型中使用它。由于其他原因,我已经扩展了 CI_Model 和 CI_Controller。将观察者模式代码放在那里是最好的吗?
我想像这样的一点:有人点击网站并产生一个请求,该请求被路由到控制器/动作:http://localhost/test/save_changes
// warning, pseudo-code!
class Test extends MY_Model
{
public function __construct ()
{
// do I put this here?!? - or maybe in MY_Model?
// Should it be a singleton?
$this->load->library('dispatcher');
// where do I attach what I want... here?
$this->load->library('emailer');
$this->dispatcher->attach($this->emailer);
// what if I have 50 possible things that might happen
// based on any given event, from adding a user to
// deleting a survey or document? There has got to be a
// way to attach a bunch of observers that trickle
// down to each object, right?
}
public function save_changes ()
{
$this->load->model('user');
$this->user->init($this->session->userdata('user.id'))->save();
}
}
class User extends MY_Model
{
public function __construct ()
{
parent::__construct ();
// do I put this here?!?
$this->load->library('dispatcher'); // just something to call it
}
public function init($id)
{
if($this->_loadUser ($id))
{
$this->dispatcher->notify($this, 'user.loaded');
}
}
public function save($id)
{
if(parent::save())
{
$this->dispatcher->notify($this, 'user.saved');
}
}
}
class Emailer
{
public function update ($caller,$msg)
{
switch ($msg)
{
case 'user.saved':
// send user an email
// re-cache some stuff
// other things that we might want to do, including more of these:
$this->dispatch->notify('user-saved-email-sent');
break;
}
}
}
class Dispatcher
{
public function notify ($caller, $msg) { ...foreach attached do $obj->update($caller,$msg) ...}
public function attach ($obj) { ... }
public function detach ($obj) { ... }
}
我可以看到那将是多么强大。但我不确定如何简化所有这些侦听器/观察器的设置和附加。
也许我应该有一个工厂来创建它们?看起来是的,它们将与当前的工作方式分离,但似乎管理我必须在每个控制器或方法中“附加”的所有不同对象将以不同的方式耦合。
谢谢, 汉斯
【问题讨论】:
标签: codeigniter observer-pattern