1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 |
<?php // 在JS中写事件很简单 // <input type="button" value="test" onclick="test();"> // function test (){ // alert('hello world'); // } //onclick是一个事件。test()是一个响应,即:回调函数。 //那么php中,这种事件是怎么实现的呢? //比如:set_error_handler(callback_error_handler [, int error_types]) //callback_error_handler是我们自定义的一个方法,同样我们在里面输出hello world。如果php程序执行出错,就会调用这个方法 //那么我们可以理解为:程序出错是一个事件,输出hello world 是一个响应。 //由此,我们可以推断,不管什么语言。它们的事件监听都是依靠回调函数来完成的。 //比如说,我们要煮一碗面,那么先要烧水、水开了放面、然后放辅料、调料、煮完撩起。 class Pan{ protected $name = '锅子'; public function __construct() { echo $this->name . '准备好了,开始煮面...<br>'; } public function fill($obj) { echo '放入' . $obj->getName() . '...<br>'; } public function warm($time) { echo '加热' . $time . '分钟...<br>'; } public function __destruct() { echo '煮完了可以吃了...'; } } class Water{ private $name = '水'; public function getName(){ return $this->name; } } class Noodles{ private $name = '面'; public function getName(){ return $this->name; } } class Food{ private $name = '辅料'; public function getName(){ return $this->name; } } class Spices{ private $name = '调料'; public function getName(){ return $this->name; } } $pan = new Pan(); $pan->fill(new Water()); $pan->warm(5); $pan->fill(new Noodles()); $pan->warm(2); $pan->fill(new Food()); $pan->warm(2); $pan->fill(new Spices()); $pan->warm(1); //通常,我们会像上面那样依次执行我们程序。 //然后,我们通过事件来实现下上面的程序。 class Event{ private $time = -1; private $eventList = array(); public function addListen($time, $callback, $params=array()){ $this->eventList[$time][] = array($callback, $params); } public function listen(){ while ($this->eventList) { ++$this->time; if (!isset($this->eventList[$this->time])) { continue; } $this->executeEvent(); } } public function executeEvent(){ foreach ($this->eventList[$this->time] as $v) { call_user_func_array($v[0], $v[1]); } unset($this->eventList[$this->time]); } } class AutoPan extends Pan{ private $event; public function addEvent(Event $event) { $this->event = $event; } public function start() { $this->event->listen(); } } unset($pan); echo '<br><br><br>'; $event = new Event(); $pan = new AutoPan(); $pan->addEvent($event); $event->addListen(0, array($pan, 'fill'), array(new Water)); $event->addListen(0, array($pan, 'warm'), array(5)); $event->addListen(5, array($pan, 'fill'), array(new Noodles)); $event->addListen(5, array($pan, 'warm'), array(2)); $event->addListen(7, array($pan, 'fill'), array(new Food)); $event->addListen(7, array($pan, 'warm'), array(2)); $event->addListen(9, array($pan, 'fill'), array(new Spices)); $event->addListen(9, array($pan, 'warm'), array(1)); $pan->start(); |