<?php class Listener { public static function handle() { static $count = 0; return function(Event $event) use ($count) { echo "eventName=" . $event->name . " and count=" . $count . "-----in listener function<br>"; $count += 1; }; } } abstract class Event { public $name; public $callback = []; public function __construct($name) { $this->name = $name; } public function registerListener(Closure $callback) { if(! is_callable($callback)) { throw new Exception("callback is not callable", 1); } $this->callback[] = $callback; } public function setUp() { static::handle(); foreach ($this->callback as $callback) { call_user_func($callback, $this); } } abstract public function handle(); } class SaleEvent extends Event { public function handle() { echo "handle function in SaleEvent<br>"; } } function init() { return $kernel = [ 'SaleEvent' => [ 'Listener', ] ]; } function event(Event $event) { $relations = init(); $className = get_class($event); $listeners = $relations[$className]; foreach ($listeners as $value) { $event->registerListener($value::handle()); } return $event->setUp(); } event(new SaleEvent('saled'));
这样以后如果有其他监听该事件的listener,直接添加进kernel数组即可。