Update: 2026-05-06 05:11:51
This commit is contained in:
60
app/Core/Cache.php
Normal file
60
app/Core/Cache.php
Normal file
@@ -0,0 +1,60 @@
|
||||
<?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]);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user