BaseTask.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Master\Framework\Extend;
  4. use App\Utils\LogUtil;
  5. use Hyperf\Coroutine\Coroutine;
  6. class BaseTask{
  7. //日志板块
  8. protected string $LOG_MODULE = 'BaseTask';
  9. protected string $message = 'error';
  10. protected mixed $data = [];
  11. public function __construct()
  12. {
  13. //日志统一写入
  14. LogUtil::getInstance('Task/');//设置日志存入通道
  15. Coroutine::defer(function () {
  16. LogUtil::close();//协程结束后统一写入
  17. });
  18. }
  19. public function execute(): bool
  20. {
  21. LogUtil::info('开始处理', $this->LOG_MODULE, 'do');
  22. // 根据参数处理具体逻辑
  23. // 通过具体参数获取模型等
  24. // 这里的逻辑会在 ConsumerProcess 进程中执行
  25. $res = $this->do();
  26. LogUtil::info('处理结果', $this->LOG_MODULE, 'do', [
  27. 'code' => $res,
  28. 'message' => $this->getMessage(),
  29. 'data' => $this->getData(),
  30. ]);
  31. return $res;
  32. }
  33. /**
  34. * 开始工作
  35. * @return true
  36. */
  37. protected function do(): bool
  38. {
  39. // 业务代码
  40. return $this->success('执行成功');
  41. }
  42. /**
  43. * 返回成功结果
  44. * @param string $message
  45. * @param mixed $data
  46. * @return bool
  47. */
  48. protected function success(string $message = 'success', mixed $data = []): bool
  49. {
  50. $this->message = $message;
  51. $this->data = $data;
  52. return true;
  53. }
  54. /**
  55. * 返回失败结果
  56. * @param string $message
  57. * @param mixed $data
  58. * @return bool
  59. */
  60. protected function error(string $message = 'error', mixed $data = []): bool
  61. {
  62. $this->message = $message;
  63. $this->data = $data;
  64. return false;
  65. }
  66. /**
  67. * 获取成功数据
  68. * @return mixed
  69. */
  70. public function getData(): mixed
  71. {
  72. return $this->data;
  73. }
  74. /**
  75. * 获取消息
  76. * @return string
  77. */
  78. public function getMessage(): string
  79. {
  80. return $this->message;
  81. }
  82. }