thinkphp5.x没有像thinkphp6.x那样有封装了事件方法,也就没有办法直接event("事件")来调用
如果遇到复杂的逻辑想使用观察者模式就可以自己封装事件方法
在config目录里添加event.php用于指定事件目录:
<?php return [ 'listen' =>[ \app\event\OrderRefund::class=>[ \app\listener\orderRefund\PartOrderRefund::class, \app\listener\orderRefund\AllOrderRefund::class ] ] ];
在common.php里面封装 event方法
function event($event) { $eventList = config("event.listen"); if (!is_object($event)) { $event = new $event(); } $eventKey = get_class($event); if (!class_exists($eventKey)) throw new \Exception('事件类不存在!'); foreach ($eventList[$eventKey] as $listener => $class) { if (!class_exists($class)) throw new \Exception('监听类不存在!'); $obj = new $class(); if (!method_exists($class, "handle")) throw new \Exception('监听方法不存在!'); $obj->handle($event); } }
于是就可以用过调用event(class名称) 来试用事件,就能用到thinkphp5.x的观察着模式 也有点类似 管道模式