proxitok/helpers/CacheEngines/RedisCache.php

34 lines
929 B
PHP
Raw Normal View History

2022-01-14 13:26:07 -05:00
<?php
namespace Helpers\CacheEngines;
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
}
public function set(string $cache_key, mixed $data, $timeout = 3600) {
$this->client->set($cache_key, json_encode($data), $timeout);
}
}