Redis Client for PHP: Predis and PhpRedis
Redis is a high-performance key-value data store that operates in memory. There are two main approaches for interacting with Redis from PHP: the pure PHP library Predis and the native extension PhpRedis. In this article, we will cover both tools in detail, including their installation, basic commands, and practical usage examples.
1. Predis – Pure PHP Redis Client
Predis is a library written entirely in PHP that does not require installing additional extensions. It is ideal for environments where compiling C extensions is not possible.
Installation via Composer
composer require predis/predisBasic Connection and Examples
require 'vendor/autoload.php';
use Predis\\Client;
// Default connection (localhost:6379)$redis = new Client();
// Alternatively with explicit parameters$redis = new Client([ 'scheme' => 'tcp', 'host' => '127.0.0.1', 'port' => 6379, 'password' => 'secret', // if set]);
// Working with simple strings$redis->set('user:1:name', 'Alexey');echo $redis->get('user:1:name'); // Alexey
// Working with lists$redis->rpush('queue:tasks', 'task1', 'task2', 'task3');$task = $redis->lpop('queue:tasks'); // task1
// Working with hashes$redis->hset('user:1', 'email', 'alex@example.com');$redis->hset('user:1', 'age', 30);$userData = $redis->hgetall('user:1');// ['email' => 'alex@example.com', 'age' => '30']Caching with TTL (Time to Live)
// Save data for 1 hour (3600 seconds)$redis->setex('weather:spb', 3600, '{"temp": 15, "humidity": 70}');
// Check if the key existsif ($redis->exists('weather:spb')) { echo $redis->get('weather:spb');} else { // Request to external API and save $data = json_encode(['temp' => 15, 'humidity' => 70]); $redis->setex('weather:spb', 3600, $data);}Task Queues (Lists)
// Add a task to the queue$redis->rpush('email:queue', json_encode([ 'to' => 'user@example.com', 'subject' => 'Greeting', 'body' => 'Welcome!']));
// Worker: get a task (blocking mode)while (true) { $taskRaw = $redis->blpop('email:queue', 5); // timeout 5 seconds if ($taskRaw) { $task = json_decode($taskRaw[1], true); sendEmail($task['to'], $task['subject'], $task['body']); }}2. PhpRedis – Native C Extension
PhpRedis is a PHP extension written in C. It works significantly faster than Predis due to minimal overhead. It requires installation via PECL or compilation.
Installation
# Via PECL (recommended)pecl install redis
# Or manually (Linux)git clone https://github.com/phpredis/phpredis.gitcd phpredisphpize./configuremake && make install# Add extension=redis.so to php.iniUsage Examples
// Connection$redis = new Redis();$redis->connect('127.0.0.1', 6379);$redis->auth('password'); // if password is set
// Set / Get$redis->set('counter', 1);$redis->incr('counter');echo $redis->get('counter'); // 2
// Working with sets$redis->sadd('users:online', 'user1', 'user2', 'user3');$onlineCount = $redis->scard('users:online'); // 3$isOnline = $redis->sismember('users:online', 'user2'); // true
// Pub/Sub (publisher)$redis->publish('channel:news', 'New message!');
// Pub/Sub (subscriber – separate script)$redis->subscribe(['channel:news'], function ($redis, $channel, $message) { echo "Received from $channel: $message";});Caching Complex Structures
// Cache the result of an SQL query$cacheKey = 'articles:l