client = new Client($config); } /** * 获取单例实例 * @param array $config * @return HttpClient */ public static function instance(array $config = []) { if (!static::$instance instanceof static) { static::$instance = new static($config); } return static::$instance; } /** * 发送 PSR-7 请求并返回 PSR-7 响应 * * @param RequestInterface $request * @return ResponseInterface * @throws ClientExceptionInterface 如果发生错误且无法完成请求 */ public function sendRequest(RequestInterface $request): ResponseInterface { try { return $this->client->send($request); } catch (RequestException $e) { // 将 GuzzleHttp 异常转换为 PSR 客户端异常 throw new class($e->getMessage(), $e->getCode(), $e) extends \RuntimeException implements ClientExceptionInterface { // PSR ClientExceptionInterface 实现 }; } } /** * 魔术方法,将其他方法调用代理到 GuzzleHttp Client * 使其能够当作 GuzzleHttp\Client 使用 * * @param string $method * @param array $arguments * @return mixed */ public function __call($method, $arguments) { return $this->client->{$method}(...$arguments); } /** * 获取底层的 GuzzleHttp Client * @return Client */ public function getClient() { return $this->client; } /** * 设置 GuzzleHttp Client * @param Client $client * @return $this */ public function setClient(Client $client) { $this->client = $client; return $this; } }