Refactor CacheLayer to improve Redis instance management by returning null if caching is disabled and handling connection errors more gracefully.
This commit is contained in:
parent
99e811086c
commit
54b401b944
1 changed files with 41 additions and 6 deletions
|
@ -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;
|
||||
}
|
||||
}
|
Loading…
Add table
Reference in a new issue