Predis (Redis Client)
The artiframe add redis extension integrates the predis/predis package, wrapping your Redis operations under the src/Service/RedisCache.php class.
Redis provides lightning-fast In-Memory operations instead of straining your database with repetitive queries. It is ideal for saving session states, API caches, or rate limits.
Add the extension to your project via the terminal:
$ artiframe add redis
Then, the connection configurations will be added to your .env file. (A standard local Redis installation usually runs on 127.0.0.1 and port 6379 without a password.)
REDIS_HOST=127.0.0.1
REDIS_PORT=6379
REDIS_PASSWORD=null
The most common usage of Redis is to hold (Set) a value temporarily and retrieve it (Get) extremely fast.
<?php
use Src\Service\RedisCache;
$redis = new RedisCache();
// 1. Is there data in the Cache?
$cachedData = $redis->get('homepage_products');
if ($cachedData) {
// Bring it lightning fast from Redis!
echo $cachedData;
} else {
// Get it from DB (heavy operation)
$products = '[{"id":1, "name":"Laptop"}]'; // Database Simulation
// 2. Set to Cache (Expires in 3600 seconds = 1 hour)
$redis->set('homepage_products', $products, 3600);
echo $products;
}
Redis is more than just key-value pairs; it supports atomic operations (like incrementing) and data structures like Arrays/Lists.
If you perform this with SQL (UPDATE visits = visits + 1), it may lock under high traffic. Redis does this atomically.
<?php
// Increments the view count of article 42 by 1
$views = $redis->increment('article:42:views');
echo "This article has been read {$views} times.";
Since Redis holds Strings, you must encode Arrays/Objects as JSON before sending them.
<?php
// Set Array
$user = ['id' => 5, 'role' => 'admin'];
$redis->set('user:5:session', json_encode($user));
// Get Array
$data = $redis->get('user:5:session');
$decodedUser = json_decode($data, true);
When an admin adds a new product, you need to wipe out the old cache so that the users can see the updated version.
<?php
// Deletes a single key
$redis->delete('homepage_products');
// Deletes multiple keys
$redis->deleteMultiple(['homepage_products', 'categories_list']);
If the helper methods in RedisCache.php (set, get, delete) aren't enough for you and you want to use raw Redis commands (RPUSH, HMSET, ZADD), you can directly access the core Predis\Client instance.
<?php
$client = $redis->getClient();
// Raw Redis Commands
$client->lpush('task_queue', 'task_1');
$client->hset('user:100', 'name', 'Ahmet');