Files
saqel/backend/app/Core/RedisClient.php
T

70 lines
2.2 KiB
PHP

<?php
namespace App\Core;
/**
* Core Redis Client for managing connections.
* Strict environment variable enforcement (No default fallbacks).
*/
class RedisClient
{
private static ?\Redis $instance = null;
/**
* Get the singleton Redis connection instance
*/
public static function getInstance(): \Redis
{
if (self::$instance === null) {
$host = getenv('REDIS_HOST');
$port = getenv('REDIS_PORT');
$password = getenv('REDIS_PASSWORD') ?: null;
$missing = [];
if ($host === false || $host === '') $missing[] = 'REDIS_HOST';
if ($port === false || $port === '') $missing[] = 'REDIS_PORT';
if (!empty($missing)) {
throw new \RuntimeException("Redis Configuration Error: Missing environment variable(s): " . implode(', ', $missing));
}
try {
$redis = new \Redis();
// Connect with a 2.5 second timeout
if (!$redis->connect($host, (int)$port, 2.5)) {
throw new \RuntimeException("Could not connect to Redis server at {$host}:{$port}");
}
// Authenticate if password is provided
if ($password) {
if (!$redis->auth($password)) {
throw new \RuntimeException("Redis authentication failed for host {$host}:{$port}.");
}
}
// Set prefix for Saqel to avoid collisions
$redis->setOption(\Redis::OPT_PREFIX, 'saqel:');
self::$instance = $redis;
} catch (\Exception $e) {
error_log("Redis Connection Error: " . $e->getMessage());
throw new \RuntimeException("Redis connection failed ({$host}:{$port}): " . $e->getMessage());
}
}
return self::$instance;
}
/**
* Helper to close the connection explicitly
*/
public static function close(): void
{
if (self::$instance !== null) {
self::$instance->close();
self::$instance = null;
}
}
}