From 54b401b944eecb97b2b022816531518df332eb18 Mon Sep 17 00:00:00 2001 From: netkas Date: Thu, 13 Mar 2025 13:57:21 -0400 Subject: [PATCH] Refactor CacheLayer to improve Redis instance management by returning null if caching is disabled and handling connection errors more gracefully. --- src/Socialbox/Classes/CacheLayer.php | 47 ++++++++++++++++++++++++---- 1 file changed, 41 insertions(+), 6 deletions(-) diff --git a/src/Socialbox/Classes/CacheLayer.php b/src/Socialbox/Classes/CacheLayer.php index f9d48a5..64d6009 100644 --- a/src/Socialbox/Classes/CacheLayer.php +++ b/src/Socialbox/Classes/CacheLayer.php @@ -2,17 +2,52 @@ namespace Socialbox\Classes; + use Exception; + use Redis; + class CacheLayer { - private static CacheLayer $instance; - - public static function getInstance(): CacheLayer + private static ?Redis $instance = null; + + /** + * Get the Redis instance, returns null if caching is turned off or there was an error connecting + * to the Redis server. + * + * @return Redis|null + */ + public static function getInstance(): ?Redis { - if (!isset(self::$instance)) + // Return null if caching is turned off + if(!Configuration::getCacheConfiguration()->isEnabled()) { - self::$instance = new CacheLayer(); + return null; } - + + if (self::$instance === null) + { + try + { + self::$instance = new Redis(); + self::$instance->connect( + Configuration::getCacheConfiguration()->getHost(), + Configuration::getCacheConfiguration()->getPort() + ); + + if(Configuration::getCacheConfiguration()->getPassword() !== null) + { + self::$instance->auth(Configuration::getCacheConfiguration()->getPassword()); + } + + self::$instance->select(Configuration::getCacheConfiguration()->getDatabase()); + } + catch (Exception $e) + { + self::$instance = null; + Logger::getLogger()->critical($e->getMessage(), $e); + return null; + } + } + return self::$instance; } } \ No newline at end of file