From d731198aa67de637dbbb74b893de6b86b1cd4682 Mon Sep 17 00:00:00 2001 From: Kijin Sung Date: Sun, 23 Apr 2023 00:26:27 +0900 Subject: [PATCH] Cache and reuse the Guzzle client for multiple requests --- common/framework/HTTP.php | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/common/framework/HTTP.php b/common/framework/HTTP.php index 8ca67688d..d76ea261b 100644 --- a/common/framework/HTTP.php +++ b/common/framework/HTTP.php @@ -12,6 +12,19 @@ class HTTP */ public const DEFAULT_TIMEOUT = 3; + /** + * Cache the Guzzle client instance here. + */ + protected static $_client = null; + + /** + * Reset the Guzzle client instance. + */ + public static function resetClient(): void + { + self::$_client = null; + } + /** * Make a GET request. * @@ -160,9 +173,12 @@ class HTTP } // Send the request. - $guzzle = new \GuzzleHttp\Client(); + if (!self::$_client) + { + self::$_client = new \GuzzleHttp\Client(); + } $start_time = microtime(true); - $response = $guzzle->request($method, $url, $settings); + $response = self::$_client->request($method, $url, $settings); $status_code = $response->getStatusCode() ?: 0; // Measure elapsed time and add a debug entry.