Library.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Master\Framework\Library;
  4. use GuzzleHttp\Client;
  5. use GuzzleHttp\RequestOptions;
  6. use Hyperf\Guzzle\HandlerStackFactory;
  7. /**
  8. * 扩展返回工具
  9. */
  10. class Library
  11. {
  12. protected string $base_uri = 'http://127.0.0.1:9501';
  13. protected string $message = 'error';
  14. protected mixed $data = [];
  15. /**
  16. * post json 请求
  17. *
  18. * @param string $uri
  19. * @param array $params
  20. * @param array $header
  21. * @return \Psr\Http\Message\ResponseInterface
  22. * @throws \GuzzleHttp\Exception\GuzzleException
  23. */
  24. protected function postJson(string $uri, array $params = [], array $header = [])
  25. {
  26. $factory = new HandlerStackFactory();
  27. $stack = $factory->create();
  28. $client = new Client([
  29. // guzzle http里的配置信息
  30. 'base_uri' => $this->base_uri,
  31. 'handler' => $stack,
  32. 'timeout' => 5,
  33. // swoole的配置信息,内容会覆盖guzzle http里的配置信息
  34. 'swoole' => [
  35. 'timeout' => 10,
  36. 'socket_buffer_size' => 1024 * 1024 * 2,
  37. ],
  38. ]);
  39. return $client->post($uri, [
  40. RequestOptions::JSON => $params,
  41. RequestOptions::VERIFY => false,
  42. RequestOptions::HEADERS => array_merge(
  43. $header,
  44. [
  45. 'Content-Type' => 'application/json'
  46. ]
  47. ),
  48. ]);
  49. }
  50. /**
  51. * 返回成功结果
  52. * @param string $message
  53. * @param mixed $data
  54. * @return bool
  55. */
  56. protected function success(string $message = 'success', mixed $data = []): bool
  57. {
  58. $this->message = $message;
  59. $this->data = $data;
  60. return true;
  61. }
  62. /**
  63. * 返回失败结果
  64. * @param string $message
  65. * @param mixed $data
  66. * @return bool
  67. */
  68. protected function error(string $message = 'error', mixed $data = []): bool
  69. {
  70. $this->message = $message;
  71. $this->data = $data;
  72. return false;
  73. }
  74. /**
  75. * 获取成功数据
  76. * @return mixed
  77. */
  78. public function getData(): mixed
  79. {
  80. return $this->data;
  81. }
  82. /**
  83. * 获取消息
  84. * @return string
  85. */
  86. public function getMessage(): string
  87. {
  88. return $this->message;
  89. }
  90. }