proxitok/app/Cache/RedisCache.php

37 lines
1 KiB
PHP
Raw Normal View History

2022-01-14 18:26:07 +00:00
<?php
2022-01-30 23:02:52 +00:00
namespace App\Cache;
2022-01-14 18:26:07 +00:00
2022-09-25 17:53:00 +00:00
use TikScraper\Interfaces\CacheInterface;
class RedisCache implements CacheInterface {
2022-01-14 18:26:07 +00:00
private \Redis $client;
function __construct(string $host, int $port, ?string $password) {
2022-01-14 18:31:08 +00:00
$this->client = new \Redis();
2022-01-17 20:11:40 +00:00
if (!$this->client->connect($host, $port)) {
throw new \Exception('REDIS: Could not connnect to server');
}
2022-01-14 18:26:07 +00:00
if ($password) {
2022-01-17 20:11:40 +00:00
if (!$this->client->auth($password)) {
throw new \Exception('REDIS: Could not authenticate');
}
2022-01-14 18:26:07 +00:00
}
}
function __destruct() {
$this->client->close();
}
2022-01-17 20:11:40 +00:00
public function get(string $cache_key): ?object {
$data = $this->client->get($cache_key);
return $data ? json_decode($data) : null;
2022-01-14 18:26:07 +00:00
}
2022-03-11 22:18:26 +00: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 18:26:07 +00:00
}
}