63 lines
1.9 KiB
PHP
63 lines
1.9 KiB
PHP
<?php
|
|
|
|
namespace App\Core;
|
|
|
|
/**
|
|
* Core Redis Client for managing connections.
|
|
* Handles Sessions, Rate Limiting, and caching using PHP Redis extension.
|
|
*/
|
|
class RedisClient
|
|
{
|
|
private static ?\Redis $instance = null;
|
|
|
|
/**
|
|
* Get the singleton Redis connection instance
|
|
*/
|
|
public static function getInstance(): \Redis
|
|
{
|
|
if (self::$instance === null) {
|
|
try {
|
|
$redis = new \Redis();
|
|
|
|
$host = getenv('REDIS_HOST') ?: '127.0.0.1';
|
|
$port = (int)(getenv('REDIS_PORT') ?: 6379);
|
|
$password = getenv('REDIS_PASSWORD') ?: null;
|
|
|
|
// Connect with a 2 second timeout
|
|
if (!$redis->connect($host, $port, 2.0)) {
|
|
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.");
|
|
}
|
|
}
|
|
|
|
// Set prefix for Saqel to avoid collisions
|
|
$redis->setOption(\Redis::OPT_PREFIX, 'saqel:');
|
|
|
|
self::$instance = $redis;
|
|
} catch (\Exception $e) {
|
|
// In production, fallback gracefully or throw HTTP 500
|
|
error_log("Redis Connection Error: " . $e->getMessage());
|
|
throw new \RuntimeException("Redis is unavailable. Please ensure the Redis server is running.");
|
|
}
|
|
}
|
|
|
|
return self::$instance;
|
|
}
|
|
|
|
/**
|
|
* Helper to close the connection explicitly
|
|
*/
|
|
public static function close(): void
|
|
{
|
|
if (self::$instance !== null) {
|
|
self::$instance->close();
|
|
self::$instance = null;
|
|
}
|
|
}
|
|
}
|