Predis

PHPCache LibraryRedisClientNoSQL

GitHub Overview

predis/predis

A flexible and feature-complete Redis/Valkey client for PHP.

Stars7,727
Watchers208
Forks993
Created:November 7, 2009
Language:PHP
License:MIT License

Topics

phppredisredisredis-clusterredis-sentinel

Star History

predis/predis Star History
Data as of: 10/22/2025, 08:07 AM

Cache Library

Predis

Overview

Predis is a flexible and feature-complete Redis client library for PHP that enables communication with Redis servers and other RESP (Redis Serialization Protocol) compatible key-value stores like Valkey.

Details

Predis is a Redis client library written entirely in PHP that doesn't require any additional C extensions. It supports connections via TCP/IP (including TLS/SSL encryption) and UNIX domain sockets, with both lazy and persistent connection capabilities. The library supports a wide range of Redis features including transactions, pipelining, clustering, Pub/Sub, abstraction for SCAN commands (SCAN, SSCAN, ZSCAN, HSCAN) based on PHP iterators, and the ability to define custom commands. It's officially supported by the Laravel framework and serves as a fallback option when the PhpRedis extension is not installed. Predis is compatible with Composer package management and provides PSR-4 compliant autoloading. It's particularly valuable in shared hosting environments and Docker containers where installing C extensions might be challenging. The library continues to be actively maintained and remains a popular choice for PHP developers in 2024, especially those who prefer a pure PHP solution.

Pros and Cons

Pros

  • Pure PHP Implementation: No C extensions required, works in any PHP environment
  • Rich Connection Options: TCP/IP, TLS/SSL, and UNIX socket support
  • Laravel Integration: Standard support and easy configuration in Laravel
  • Advanced Redis Features: Clustering, pipelining, and transaction support
  • Customizability: Ability to define custom commands and connection classes
  • SCAN Abstraction: PHP iterator-based SCAN command support
  • Composer Compatible: Integration with standard PHP package management

Cons

  • Performance: Slower processing compared to PhpRedis (C extension)
  • Memory Usage: Higher memory consumption due to pure PHP implementation
  • High-Volume Limitations: Not ideal for high-frequency, large-volume Redis operations
  • Debugging Complexity: Low-level debugging can be difficult with PHP implementation
  • Type Safety: Potential runtime errors due to dynamic typing

Key Links

Example Usage

Basic Connection

<?php
require 'vendor/autoload.php';
use Predis\Client as PredisClient;

// Basic connection
$redis = new PredisClient();

// Configured connection
$redis = new PredisClient([
    'scheme' => 'tcp',
    'host' => '127.0.0.1',
    'port' => 6379,
    'password' => '',
    'database' => 0,
]);

// Connection test
echo $redis->ping(); // PONG

Basic Key-Value Operations

// Set and get strings
$redis->set('user:1:name', 'John Doe');
$name = $redis->get('user:1:name');
echo $name; // John Doe

// Set key with expiration
$redis->setex('session:abc123', 3600, 'session_data');

// Check key existence
if ($redis->exists('user:1:name')) {
    echo "Key exists";
}

// Delete key
$redis->del('user:1:name');

List Operations

// Add elements to list
$redis->lpush('notifications', 'message1');
$redis->rpush('notifications', 'message2');
$redis->lpush('notifications', 'message3');

// Get list contents
$messages = $redis->lrange('notifications', 0, -1);
print_r($messages); // ['message3', 'message1', 'message2']

// Pop element from list
$latest = $redis->lpop('notifications');
echo $latest; // message3

Hash Operations

// Set hash fields
$redis->hset('user:1', 'name', 'Alice');
$redis->hset('user:1', 'email', '[email protected]');
$redis->hset('user:1', 'age', 30);

// Set multiple fields at once
$redis->hmset('user:2', [
    'name' => 'Bob',
    'email' => '[email protected]',
    'age' => 25
]);

// Get hash fields
$name = $redis->hget('user:1', 'name');
$userData = $redis->hgetall('user:1');
print_r($userData);

Pipelining

// Execute multiple commands efficiently with pipeline
$pipe = $redis->pipeline();
$pipe->set('key1', 'value1');
$pipe->set('key2', 'value2');
$pipe->set('key3', 'value3');
$pipe->get('key1');
$pipe->get('key2');
$results = $pipe->execute();

print_r($results); // [OK, OK, OK, 'value1', 'value2']

Pub/Sub

// Publisher
$redis->publish('notifications', 'Hello, subscribers!');

// Subscriber
$pubsub = $redis->pubSubLoop();
$pubsub->subscribe('notifications');

foreach ($pubsub as $message) {
    switch ($message->kind) {
        case 'subscribe':
            echo "Subscribed to {$message->channel}\n";
            break;
        case 'message':
            echo "Received: {$message->payload}\n";
            break;
    }
}

Laravel Integration Example

// Configuration in config/database.php
'redis' => [
    'client' => env('REDIS_CLIENT', 'predis'),
    'options' => [
        'cluster' => env('REDIS_CLUSTER', 'redis'),
        'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'),
    ],
    'default' => [
        'url' => env('REDIS_URL'),
        'host' => env('REDIS_HOST', '127.0.0.1'),
        'password' => env('REDIS_PASSWORD'),
        'port' => env('REDIS_PORT', '6379'),
        'database' => env('REDIS_DB', '0'),
    ],
],

// Usage in Laravel
use Illuminate\Support\Facades\Redis;

// Basic operations
Redis::set('user:1:name', 'John');
$name = Redis::get('user:1:name');

// Cache usage
Cache::store('redis')->put('key', 'value', 3600);
$value = Cache::store('redis')->get('key');