Notify.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. namespace addons\shopro\library\notify;
  3. use think\queue\ShouldQueue;
  4. class Notify
  5. {
  6. public function sendNotify($notifiables, $notification) {
  7. if ($notification instanceof ShouldQueue) {
  8. // 队列执行
  9. return $this->sendQueueNotify($notifiables, $notification, $notification->delay);
  10. }
  11. return $this->sendNowNotify($notifiables, $notification);
  12. }
  13. /**
  14. * 立即发送
  15. */
  16. public function sendNowNotify($notifiables, $notification) {
  17. foreach ($notifiables as $key => $notifiable) {
  18. $channels = $notification->channels($notifiable);
  19. if (empty($channels)) {
  20. continue;
  21. }
  22. foreach ($channels as $k => $channel) {
  23. (new $channel)->send($notifiable, $notification);
  24. }
  25. }
  26. }
  27. /**
  28. * 队列发送
  29. * delay 延迟时间
  30. */
  31. public function sendQueueNotify($notifiables, $notification, $delay) {
  32. $notifiables = $notifiables instanceof \think\Collection ? $notifiables->all() : collection($notifiables)->all();
  33. if ($delay > 0) {
  34. // 异步延迟发送
  35. \think\Queue::later($delay, '\addons\shopro\job\Notification@send', [
  36. 'notifiables' => $notifiables,
  37. 'notifiable_name' => get_class(reset($notifiables)),
  38. 'notification' => $notification,
  39. 'notification_name' => get_class($notification),
  40. ], 'shopro');
  41. } else {
  42. // 异步立即发送
  43. \think\Queue::push('\addons\shopro\job\Notification@send', [
  44. 'notifiables' => $notifiables,
  45. 'notifiable_name' => get_class(reset($notifiables)),
  46. 'notification' => $notification,
  47. 'notification_name' => get_class($notification)
  48. ], 'shopro');
  49. }
  50. }
  51. public static function __callStatic($name, $arguments)
  52. {
  53. return (new self)->{$name . 'Notify'}(...$arguments);
  54. }
  55. }