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.

1. Installation and Configuration

Add the extension to your project via the terminal:

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.)

.env
REDIS_HOST=127.0.0.1
REDIS_PORT=6379
REDIS_PASSWORD=null
2. Basic Set and Get Operations (Cache)

The most common usage of Redis is to hold (Set) a value temporarily and retrieve it (Get) extremely fast.

ProductController.php
<?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;
}
3. Advanced Commands

Redis is more than just key-value pairs; it supports atomic operations (like incrementing) and data structures like Arrays/Lists.

1. Increment / Decrement (Page Views, Limits)

If you perform this with SQL (UPDATE visits = visits + 1), it may lock under high traffic. Redis does this atomically.

example.php
<?php
// Increments the view count of article 42 by 1
$views = $redis->increment('article:42:views');

echo "This article has been read {$views} times.";
2. Saving Arrays / Objects (JSON)

Since Redis holds Strings, you must encode Arrays/Objects as JSON before sending them.

example.php
<?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);
3. Deleting Cache (Invalidation)

When an admin adds a new product, you need to wipe out the old cache so that the users can see the updated version.

example.php
<?php
// Deletes a single key
$redis->delete('homepage_products');

// Deletes multiple keys
$redis->deleteMultiple(['homepage_products', 'categories_list']);
4. Direct Predis Client Access

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.

example.php
<?php
$client = $redis->getClient();

// Raw Redis Commands
$client->lpush('task_queue', 'task_1');
$client->hset('user:100', 'name', 'Ahmet');