From 282ad20a6b32e86c37ec54c58672744b0d0b8030 Mon Sep 17 00:00:00 2001 From: Pablo Ferreiro Date: Fri, 14 Jan 2022 19:26:07 +0100 Subject: [PATCH] Added Redis cache --- .env.example | 9 +++++++-- README.md | 1 + composer.json | 2 +- helpers/CacheEngines/RedisCache.php | 31 +++++++++++++++++++++++++++++ helpers/Misc.php | 13 ++++++++++++ 5 files changed, 53 insertions(+), 3 deletions(-) create mode 100644 helpers/CacheEngines/RedisCache.php diff --git a/.env.example b/.env.example index d005e1f..461a337 100644 --- a/.env.example +++ b/.env.example @@ -1,2 +1,7 @@ -APP_SUBDIR=/ # Subpath your app is running, defaults to / -APP_CACHE=json # Cache engine for TikTok Api, defaults to json (more info on README) +# APP_SUBDIR=/ # Subpath your app is running, defaults to / +# APP_CACHE=json # Cache engine for TikTok Api, defaults to json (more info on README) + +# Redis, used on Helpers\CahceEngines\RedisCache (CHOOSE ONE) + +# REDIS_URL=redis://:password@host:port # If using password +# REDIS_URL=redis://host:port # If not using password diff --git a/README.md b/README.md index 09a3a4d..ae2e4d7 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,7 @@ Move the .env.example file to .env and modify it. ### Cache engine Available cache engines: +* redis: Writes response to Redis (check .env.example for config!) * json: Writes response to JSON file ### Apache diff --git a/composer.json b/composer.json index 7f2b5f3..f925cbc 100644 --- a/composer.json +++ b/composer.json @@ -10,7 +10,7 @@ } ], "require": { - "ext-curl": "*", + "ext-redis": "*", "ssovit/tiktok-api": "dev-rework", "steampixel/simple-php-router": "^0.7.0", "latte/latte": "^2.10", diff --git a/helpers/CacheEngines/RedisCache.php b/helpers/CacheEngines/RedisCache.php new file mode 100644 index 0000000..58d5bb9 --- /dev/null +++ b/helpers/CacheEngines/RedisCache.php @@ -0,0 +1,31 @@ +client = new Redis(); + $this->client->connect($host, $port); + if ($password) { + $this->client->auth($password); + } + } + + function __destruct() { + $this->client->close(); + } + + public function get(string $cache_key): object|false { + if ($this->client->exists($cache_key)) { + $data_string = $this->client->get($cache_key); + return json_decode($data_string); + } + return false; + } + + public function set(string $cache_key, mixed $data, $timeout = 3600) { + $this->client->set($cache_key, json_encode($data), $timeout); + } +} diff --git a/helpers/Misc.php b/helpers/Misc.php index 9610d59..9d116a1 100644 --- a/helpers/Misc.php +++ b/helpers/Misc.php @@ -1,7 +1,9 @@