VOOZH about

URL: https://deepwiki.com/hypervel/redis/5-redisconnection

⇱ RedisConnection | hypervel/redis | DeepWiki


Loading...
Menu

RedisConnection

Purpose and Scope

This document covers the RedisConnection class, the most critical component in the Hypervel Redis system (importance: 12.20). RedisConnection extends Hyperf's RedisConnection to provide a Laravel-compatible API layer while maintaining compatibility with Hyperf's connection pooling infrastructure. It achieves this through a dual-mode transformation system controlled by the shouldTransform flag.

For details on how transformations are routed and controlled, see Transformation System. For specific command transformation implementations, see Command Transformations. For specialized scan operation handling, see Scan Operations. For pub/sub operation handling, see Pub/Sub Operations.

Sources: src/RedisConnection.php1-715

Class Overview

RedisConnection serves as a compatibility bridge between Laravel's Redis API conventions and Hyperf's Redis client, which follows PHP Redis extension conventions more closely. This allows developers familiar with Laravel to use Hyperf's high-performance Redis client without modifying their application code.

The class extends Hyperf\Redis\RedisConnection and intercepts method calls through the __call magic method, selectively transforming arguments and return values based on the shouldTransform flag.


Sources: src/RedisConnection.php260-287

Class Structure

The RedisConnection class is defined in the Hypervel\Redis namespace and contains the following key components:

ComponentTypePurpose
shouldTransformPropertyBoolean flag controlling transformation behavior
__call()MethodMagic method that intercepts all Redis command calls
shouldTransform()MethodSetter for enabling/disabling transformations
getShouldTransform()MethodGetter for current transformation state
release()MethodResets transformation state when returning to pool
call*() methodsMethodsTransformation implementations for specific commands
scan(), zscan(), etc.MethodsSpecial handling for scan operations
callSubscribe()MethodSpecial handling for pub/sub operations

Sources: src/RedisConnection.php260-714

The Magic Method Router

The __call() magic method is the central dispatch mechanism for all Redis operations. It implements a three-tier routing strategy:


The routing logic in src/RedisConnection.php267-287:

  1. Pub/Sub Priority: Subscribe operations (subscribe, psubscribe) always use callSubscribe() regardless of the shouldTransform flag, because they require special read timeout handling.

  2. Transformation Check: If shouldTransform is true, the router looks for a method named call{CommandName} (e.g., callGet for get()).

  3. Fallback to Parent: If no transformation method exists or shouldTransform is false, the call passes directly to the parent HyperfRedisConnection.

  4. Retry on Exception: All execution paths are wrapped in exception handling that delegates to the retry() method inherited from the parent class.

Sources: src/RedisConnection.php267-287

Dual-Mode Operation

The shouldTransform property enables the same connection instance to operate in two distinct modes:

ModeshouldTransformBehaviorUse Case
Laravel ModetrueCommands are intercepted and transformedDefault mode for application code expecting Laravel conventions
Hyperf ModefalseCommands pass directly to PHP Redis extensionPerformance-critical code or code already using PHP Redis conventions

Setting the Transformation Mode

The transformation mode is controlled via the shouldTransform() method:


Sources: src/RedisConnection.php299-312

Connection Lifecycle and Mode Reset

When a connection is returned to the pool via release(), the shouldTransform flag is automatically reset to false. This ensures that connections retrieved from the pool start in a clean state and transformations must be explicitly enabled.

src/RedisConnection.php289-294 shows this reset behavior:


This design prevents cross-coroutine state contamination, where one coroutine's transformation settings could affect another coroutine that reuses the same connection.

Sources: src/RedisConnection.php289-294

Transformation Categories

The RedisConnection class implements transformations across multiple Redis command categories. Each transformation addresses specific API differences between Laravel and PHP Redis conventions.


Summary of Transformation Patterns

PatternCommandsDescription
Null Conversionget, mget, blpop, brpopConvert false to null for missing keys
Argument Restructuringset, hmset, zadd, lremReorder or flatten arguments to match Laravel conventions
Return Value Transformationhmget, setnx, hsetnxConvert associative arrays to indexed arrays or cast types
Options Parsingzadd, zrangebyscore, zinterstoreExtract options from variadic arguments into structured arrays
Cursor Managementscan, zscan, hscan, sscanWrap cursor and results in array format
Timeout Handlingsubscribe, psubscribeTemporarily modify read timeout to prevent connection issues
Script LoadingevalshaAutomatically load scripts by content rather than SHA

For detailed examples of each transformation, see Command Transformations.

Sources: src/RedisConnection.php315-714

Key Transformations at a Glance

String Command Transformations

The most frequently used transformations involve string operations:

callGet() src/RedisConnection.php317-322: Returns null instead of false when a key doesn't exist, matching Laravel's convention.

callMget() src/RedisConnection.php327-332: Maps all false values in the result array to null, ensuring consistent null semantics for missing keys.

callSet() src/RedisConnection.php337-344: Restructures expiry arguments from Laravel's set($key, $value, 'EX', 60) format to PHP Redis's options array format.

Hash Command Transformations

callHmget() src/RedisConnection.php357-366: Returns array_values() instead of an associative array, matching Laravel's expectation of an indexed array.

callHmset() src/RedisConnection.php371-382: Converts variadic field-value pairs into an associative array, supporting both hmset($key, 'f1', 'v1', 'f2', 'v2') and hmset($key, ['f1' => 'v1', 'f2' => 'v2']) formats.

Sorted Set Command Transformations

callZadd() src/RedisConnection.php433-457: Parses options like 'nx', 'xx', 'ch', 'incr', 'gt', 'lt' from the argument list and restructures member-score pairs from an associative array.

Sources: src/RedisConnection.php317-513

Integration with Connection Pool

The RedisConnection class is designed to work seamlessly with Hyperf's connection pooling system. The key integration point is the release() method, which ensures proper cleanup when connections are returned to the pool.


This lifecycle ensures:

  • Each coroutine can independently set its transformation preferences
  • Connections don't leak transformation state between coroutines
  • The pool can safely reuse connections across different usage patterns

Sources: src/RedisConnection.php289-294

Comprehensive Method Documentation

The class provides extensive PHPDoc annotations for all supported Redis commands. These annotations serve two purposes:

  1. IDE Auto-completion: Provide method signatures for IDE tooling
  2. API Documentation: Document expected parameters and return types

The annotations cover all PHP Redis extension methods src/RedisConnection.php36-259 including:

  • Basic commands (get, set, del, etc.)
  • List operations (lpush, rpush, blpop, etc.)
  • Set operations (sadd, srem, sinter, etc.)
  • Sorted set operations (zadd, zrange, zrank, etc.)
  • Hash operations (hset, hget, hmget, etc.)
  • Pub/Sub operations (subscribe, publish, etc.)
  • Transaction commands (multi, exec, discard)
  • Stream commands (xadd, xread, xgroup, etc.)
  • Geo commands (geoadd, georadius, etc.)

Sources: src/RedisConnection.php16-259

Error Handling and Retry Logic

The __call() method implements a try-catch pattern that delegates exception handling to the parent class's retry() method:


This ensures that:

  • Connection failures trigger automatic reconnection attempts (handled by parent class)
  • Transformation errors are caught and retried if appropriate
  • Exception handling is consistent with Hyperf's Redis client behavior

Sources: src/RedisConnection.php282-286

Usage Pattern Summary

Typical usage follows this pattern:


For detailed transformation examples, see Command Transformations. For scan operation patterns, see Scan Operations. For pub/sub patterns, see Pub/Sub Operations.

Sources: src/RedisConnection.php1-715