事件

绑定事件

  1. 通过模块根目录 events.json 文件绑定。如
    1. [
    2. {
    3. "group_title": "分组名称",
    4. "list": [
    5. {
    6. "event": "TestEvent",
    7. "description": "事件描述",
    8. "payload": "载荷描述",
    9. "listeners": [
    10. {
    11. "name": "app\\test\\events\\Event@onTest",
    12. "description": "带方法,执行Event类onTest方法"
    13. "sort": 10,
    14. "status": 1
    15. },
    16. {
    17. "name": "app\\test\\events\\Event",
    18. "description": "不带方法,执行Event类handle方法",
    19. "sort": 10,
    20. "status": 1
    21. },
    22. ]
    23. }
    24. ]
    25. }
    26. ]
  2. 通过根目录 event.php 订阅或监听
    1. return [
    2. 'listen' => [
    3. 'Test' => [
    4. '\\app\\test\\events\\Event@test1',
    5. '\\app\\test\\events\\Event@test2'
    6. ]
    7. ],
    8. 'subscribe' => [
    9. '\\app\\test\\subscribe\\Event'
    10. ]
    11. ];
    12. // \app\test\subscribe
    13. class Event
    14. {
    15. public function onTestEvent()
    16. {
    17. echo 'event trigger';
    18. }
    19. }
  3. 动态绑定,如
    1. app(\yi\Event::class)->bind('BeforeIndexController', function($payload) {
    2. // do something
    3. });
    4. app(\yi\Event::class)->bind('BeforeIndexController', '\\app\\test\\events\\Event@test');

触发事件

  1. event('事件名称', 参数)

  2. ev('事件名称', 参数1, 参数2 ...)
    该方式带返回值,如:

    1. public function onTest($payload)
    2. {
    3. list($p1, $p2) = $payload->params; // 获取参数
    4. $payload->result = "param1: $p1, param2: $p2";
    5. }
    6. // 触发事件
    7. $data = ev('test', 'p1', 'p2');
    8. echo $data; // param1: p1, param2: p2