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,15 +2,50 @@
|
||||||
|
|
||||||
namespace Socialbox\Classes;
|
namespace Socialbox\Classes;
|
||||||
|
|
||||||
|
use Exception;
|
||||||
|
use Redis;
|
||||||
|
|
||||||
class CacheLayer
|
class CacheLayer
|
||||||
{
|
{
|
||||||
private static CacheLayer $instance;
|
private static ?Redis $instance = null;
|
||||||
|
|
||||||
public static function getInstance(): CacheLayer
|
/**
|
||||||
|
* 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;
|
return self::$instance;
|
||||||
|
|
Loading…
Add table
Reference in a new issue