Project structure change
This commit is contained in:
parent
bd1642957c
commit
837f126021
29 changed files with 298 additions and 254 deletions
33
app/Cache/JSONCache.php
Normal file
33
app/Cache/JSONCache.php
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
<?php
|
||||
namespace App\Cache;
|
||||
|
||||
class JSONCache {
|
||||
private string $cache_path = __DIR__ . '/../../cache/api';
|
||||
|
||||
function __construct() {
|
||||
if (isset($_ENV['API_CACHE_JSON']) && !empty($_ENV['API_CACHE_JSON'])) {
|
||||
$this->cache_path = $_ENV['API_CACHE_JSON'];
|
||||
}
|
||||
}
|
||||
public function get(string $cache_key): object|false {
|
||||
$filename = $this->cache_path . '/' . $cache_key . '.json';
|
||||
if (is_file($filename)) {
|
||||
$time = time();
|
||||
$json_string = file_get_contents($filename);
|
||||
$element = json_decode($json_string);
|
||||
if ($time < $element->expires) {
|
||||
return $element->data;
|
||||
}
|
||||
// Remove file if expired
|
||||
unlink($filename);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public function set(string $cache_key, mixed $data, $timeout = 3600) {
|
||||
file_put_contents($this->cache_path . '/' . $cache_key . '.json', json_encode([
|
||||
'data' => $data,
|
||||
'expires' => time() + $timeout
|
||||
]));
|
||||
}
|
||||
}
|
||||
33
app/Cache/RedisCache.php
Normal file
33
app/Cache/RedisCache.php
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
<?php
|
||||
namespace App\Cache;
|
||||
|
||||
class RedisCache {
|
||||
private \Redis $client;
|
||||
function __construct(string $host, int $port, ?string $password) {
|
||||
$this->client = new \Redis();
|
||||
if (!$this->client->connect($host, $port)) {
|
||||
throw new \Exception('REDIS: Could not connnect to server');
|
||||
}
|
||||
if ($password) {
|
||||
if (!$this->client->auth($password)) {
|
||||
throw new \Exception('REDIS: Could not authenticate');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function __destruct() {
|
||||
$this->client->close();
|
||||
}
|
||||
|
||||
public function get(string $cache_key): ?object {
|
||||
$data = $this->client->get($cache_key);
|
||||
if ($data) {
|
||||
return json_decode($data);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public function set(string $cache_key, mixed $data, $timeout = 3600) {
|
||||
$this->client->set($cache_key, json_encode($data), $timeout);
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue