akanyan/app/Redis.php
2023-08-27 21:53:01 +08:00

54 lines
1.3 KiB
PHP

<?php
namespace MingTsay\Akanyan;
use MingTsay\Akanyan\Discord\Me;
require_once __DIR__ . '/../env.php';
class Redis
{
public const PREFIX = 'akanyan:discord:me:';
public const TTL = 600; // 10 minutes
protected static ?\Redis $redis = null;
/**
* @throws \RedisException
*/
protected static function connect(): \Redis
{
if (static::$redis === null) {
static::$redis = new \Redis();
static::$redis->connect('127.0.0.1');
}
return static::$redis;
}
protected static function getKey(string $u): string
{
return static::PREFIX . md5($u);
}
public static function getCachedMe(string $u): ?Me
{
try {
$redis = static::connect();
return unserialize($redis->get(static::getKey($u))) ?: null;
} catch (\RedisException $e) {
trigger_error($e->getMessage());
return null;
}
}
public static function cacheMe(string $u, ?Me $me): ?Me
{
try {
$redis = static::connect();
$redis->setEx(static::getKey($u), static::TTL, serialize($me));
return $me;
} catch (\RedisException $e) {
trigger_error($e->getMessage());
return null;
}
}
}