一个基于PHP的事件机制

开发者在线 Builder.com.cn 更新时间:2007-07-16作者:左轻侯 来源:

本文关键词: 事件 左轻侯 php

EventUtils:

final class EventArgs {
}

interface EventHandler {
public function Invoke($Sender, EventArgs $E);
}

class Event {
private $EventHandlerList = array ();

public function AddEventHandler(EventHandler $EventHandler) {
$this->EventHandlerList[] = $EventHandler;
}

public function DeleteEventHandler(EventHandler $EventHandler) {
$Index = array_search($EventHandler, $this->EventHanlerList);
array_splice($this->EventHanlerList, $Index, 1);
}

public function Invoke($Sender, EventArgs $E) {
foreach ($this->EventHandlerList as $EventHandler) {
$EventHandler->Invoke($Sender, $E);
}
}

}

Test Case:

class TestEventHandler implements EventHandler {
public function Invoke($Sender, EventArgs $E) {
echo "Hello, ".$Sender;
}
}

function TestEvent() {
$Event = new Event();
$EventHandler = new TestEventHandler();
$Event->AddEventHandler($EventHandler);
$Event->Invoke($Event, new EventArgs());
}

Output:

Hello, Object id #5ok.

支持Multicast
麻烦的是,PHP不支持internal class,这个机制可能还要修改。

查看更多左轻侯文章

查看本文来源

用户评论

  • 用户名
  • 评论内容