ChannelService.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace crmeb\services\workerman;
  12. use Channel\Client;
  13. class ChannelService
  14. {
  15. /**
  16. * @var Client
  17. */
  18. protected $channel;
  19. /**
  20. * @var
  21. */
  22. protected $trigger = 'crmeb';
  23. /**
  24. * @var ChannelService
  25. */
  26. protected static $instance;
  27. public function __construct()
  28. {
  29. self::connet();
  30. }
  31. public static function instance()
  32. {
  33. if (is_null(self::$instance))
  34. self::$instance = new self();
  35. return self::$instance;
  36. }
  37. public static function connet()
  38. {
  39. $config = config('workerman.channel');
  40. Client::connect($config['ip'], $config['port']);
  41. }
  42. /**
  43. * @param string $name
  44. * @return $this
  45. */
  46. public function setTrigger(string $name)
  47. {
  48. $this->trigger = $name;
  49. return $this;
  50. }
  51. /**
  52. * 发送消息
  53. * @param string $type 类型
  54. * @param array|null $data 数据
  55. * @param array|null $ids 用户 id,不传为全部用户
  56. */
  57. public function send(string $type, ?array $data = null, ?array $ids = null)
  58. {
  59. $res = compact('type');
  60. if (!is_null($data))
  61. $res['data'] = $data;
  62. if (!is_null($ids) && count($ids))
  63. $res['ids'] = $ids;
  64. $this->trigger($this->trigger, $res);
  65. $this->trigger = 'crmeb';
  66. }
  67. public function trigger(string $type, ?array $data = null)
  68. {
  69. Client::publish($type, $data);
  70. }
  71. }