Initial commit: Uruk Prize Platform architecture, backend core, mobile app, gateway caller & deployment pipeline
This commit is contained in:
@@ -0,0 +1,85 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Core;
|
||||
|
||||
use Redis;
|
||||
use Throwable;
|
||||
|
||||
class RedisClient
|
||||
{
|
||||
private static ?Redis $instance = null;
|
||||
private static bool $connectionFailed = false;
|
||||
|
||||
private function __construct() {}
|
||||
private function __clone() {}
|
||||
|
||||
public static function getInstance(): ?Redis
|
||||
{
|
||||
if (self::$connectionFailed) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (self::$instance === null) {
|
||||
if (!class_exists('Redis')) {
|
||||
self::$connectionFailed = true;
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
$config = require __DIR__ . '/../config/redis.php';
|
||||
$redis = new Redis();
|
||||
$connected = $redis->connect($config['host'], $config['port'], (float)$config['timeout']);
|
||||
|
||||
if ($connected) {
|
||||
if (!empty($config['password'])) {
|
||||
$redis->auth($config['password']);
|
||||
}
|
||||
if (!empty($config['database'])) {
|
||||
$redis->select((int)$config['database']);
|
||||
}
|
||||
$redis->setOption(Redis::OPT_PREFIX, $config['prefix']);
|
||||
self::$instance = $redis;
|
||||
} else {
|
||||
self::$connectionFailed = true;
|
||||
}
|
||||
} catch (Throwable $e) {
|
||||
self::$connectionFailed = true;
|
||||
error_log('[Redis Error] ' . $e->getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return self::$instance;
|
||||
}
|
||||
|
||||
public static function get(string $key): ?string
|
||||
{
|
||||
$redis = self::getInstance();
|
||||
if (!$redis) return null;
|
||||
$val = $redis->get($key);
|
||||
return $val !== false ? (string)$val : null;
|
||||
}
|
||||
|
||||
public static function set(string $key, string $value, int $ttlSeconds = 0): bool
|
||||
{
|
||||
$redis = self::getInstance();
|
||||
if (!$redis) return false;
|
||||
return $ttlSeconds > 0 ? (bool)$redis->setex($key, $ttlSeconds, $value) : (bool)$redis->set($key, $value);
|
||||
}
|
||||
|
||||
public static function del(string $key): bool
|
||||
{
|
||||
$redis = self::getInstance();
|
||||
if (!$redis) return false;
|
||||
return (bool)$redis->del($key);
|
||||
}
|
||||
|
||||
public static function has(string $key): bool
|
||||
{
|
||||
$redis = self::getInstance();
|
||||
if (!$redis) return false;
|
||||
return (bool)$redis->exists($key);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user