Files
musadaq-saas/app/Core/Cache.php
2026-05-06 05:11:51 +03:00

61 lines
1.5 KiB
PHP

<?php
/**
* Redis Cache Wrapper
*/
declare(strict_types=1);
namespace App\Core;
class Cache
{
private static ?\Predis\Client $client = null;
public static function getInstance(): ?\Predis\Client
{
if (self::$client === null) {
$host = env('REDIS_HOST', '127.0.0.1');
$port = (int)env('REDIS_PORT', 6379);
$pass = env('REDIS_PASSWORD', null);
try {
self::$client = new \Predis\Client([
'scheme' => 'tcp',
'host' => $host,
'port' => $port,
'password' => $pass,
]);
self::$client->connect();
} catch (\Exception $e) {
error_log("Redis Connection Error: " . $e->getMessage());
return null;
}
}
return self::$client;
}
public static function set(string $key, $value, int $ttl = 3600): bool
{
$redis = self::getInstance();
if (!$redis) return false;
$redis->setex($key, $ttl, serialize($value));
return true;
}
public static function get(string $key)
{
$redis = self::getInstance();
if (!$redis) return false;
$data = $redis->get($key);
return $data ? unserialize($data) : null;
}
public static function delete(string $key): void
{
$redis = self::getInstance();
if ($redis) $redis->del([$key]);
}
}