2022-01-14 13:26:07 -05:00
|
|
|
<?php
|
2022-01-30 18:02:52 -05:00
|
|
|
namespace App\Cache;
|
2022-01-14 13:26:07 -05:00
|
|
|
|
|
|
|
class RedisCache {
|
|
|
|
private \Redis $client;
|
|
|
|
function __construct(string $host, int $port, ?string $password) {
|
2022-01-14 13:31:08 -05:00
|
|
|
$this->client = new \Redis();
|
2022-01-17 15:11:40 -05:00
|
|
|
if (!$this->client->connect($host, $port)) {
|
|
|
|
throw new \Exception('REDIS: Could not connnect to server');
|
|
|
|
}
|
2022-01-14 13:26:07 -05:00
|
|
|
if ($password) {
|
2022-01-17 15:11:40 -05:00
|
|
|
if (!$this->client->auth($password)) {
|
|
|
|
throw new \Exception('REDIS: Could not authenticate');
|
|
|
|
}
|
2022-01-14 13:26:07 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function __destruct() {
|
|
|
|
$this->client->close();
|
|
|
|
}
|
|
|
|
|
2022-01-17 15:11:40 -05:00
|
|
|
public function get(string $cache_key): ?object {
|
|
|
|
$data = $this->client->get($cache_key);
|
|
|
|
if ($data) {
|
|
|
|
return json_decode($data);
|
2022-01-14 13:26:07 -05:00
|
|
|
}
|
2022-01-17 15:11:40 -05:00
|
|
|
return null;
|
2022-01-14 13:26:07 -05:00
|
|
|
}
|
|
|
|
|
2022-03-11 17:18:26 -05:00
|
|
|
public function exists(string $cache_key): bool {
|
|
|
|
return $this->client->exists($cache_key);
|
|
|
|
}
|
|
|
|
|
|
|
|
public function set(string $cache_key, string $data, $timeout = 3600) {
|
|
|
|
$this->client->set($cache_key, $data, $timeout);
|
2022-01-14 13:26:07 -05:00
|
|
|
}
|
|
|
|
}
|