Redis - Php
Redis with Modern PHP
Section titled “Redis with Modern PHP”Integrating Redis into a modern PHP application is straightforward using Composer for dependency management. You have two main choices for a Redis client:
- PhpRedis: A PHP extension written in C. It’s extremely fast but requires installation on the server (e.g., via PECL).
- Predis: A pure PHP client library. It’s slightly slower but requires no special extensions, just a
composer require.
For new projects, starting with Predis is often easiest. We will use Predis for these examples.
1. Project Setup with Composer
Section titled “1. Project Setup with Composer”In your project directory, run the following command to add Predis to your project:
composer require predis/predisThen, include Composer’s autoloader in your PHP script.
<?php
require 'vendor/autoload.php';2. Connecting to Redis
Section titled “2. Connecting to Redis”Instantiate the Predis client. It’s good practice to wrap your Redis logic in a try...catch block to handle potential connection errors.
<?php
require 'vendor/autoload.php';
try { $redis = new Predis\Client([ 'scheme' => 'tcp', 'host' => '127.0.0.1', 'port' => 6379, ]);
echo "Connection to server successfully" . PHP_EOL; // Check connection $ping = $redis->ping(); echo "Server is running: " . $ping . PHP_EOL;
} catch (Exception $e) { die("Could not connect to Redis: " . $e->getMessage());}When the program is executed, it will produce the following result:
Connection to server successfullyServer is running: PONG3. Code Examples
Section titled “3. Code Examples”The following examples assume you have a $redis client object as shown above.
String Example
Section titled “String Example”<?php// ... (autoloader and connection)
$key = 'tutorial-name';$value = 'Modern Redis with PHP';
$redis->set($key, $value);$retrievedValue = $redis->get($key);
echo "Stored string in redis: " . $retrievedValue . PHP_EOL;List Example
Section titled “List Example”<?php// ... (autoloader and connection)
$listKey = 'frameworks';
// Clear old list items before running example$redis->del($listKey);
$redis->lpush($listKey, ['Laravel', 'Symfony', 'Yii']);
$frameworks = $redis->lrange($listKey, 0, -1);
echo "PHP Frameworks: " . PHP_EOL;print_r($frameworks);Keys Example (Using SCAN)
Section titled “Keys Example (Using SCAN)”Warning: Never use KEYS * in production as it can block your server. The safe, modern alternative is to use an iterator which leverages the SCAN command.
<?php// ... (autoloader and connection)
use Predis\Collection\Iterator\Keyspace;
// Add some sample keys for the demo$redis->set('user:1', 'Alice');$redis->set('user:2', 'Bob');$redis->set('config:theme', 'dark');
echo "\nScanning for keys with pattern 'user:*':" . PHP_EOL;
$matchingKeys = [];// Predis provides a convenient iterator that handles the SCAN logic internallyforeach (new Keyspace($redis, 'user:*') as $key) { $matchingKeys[] = $key;}
print_r($matchingKeys);Best Practices and Frameworks
Section titled “Best Practices and Frameworks”In large applications, you will typically interact with Redis through an abstraction layer provided by a framework like Laravel or Symfony. They handle the configuration, connection pooling, and provide a clean, fluent API for caching, session handling, and queueing with Redis.