VOOZH about

URL: https://deepwiki.com/hypervel/redis/4.1-basic-operations

⇱ Basic Operations | hypervel/redis | DeepWiki


Loading...
Menu

Basic Operations

Purpose and Scope

This document covers the fundamental operations of the Redis client class, including command execution, connection acquisition, and result handling. It demonstrates the typical flow of Redis operations and how the client manages the connection lifecycle.

For information about how connections are managed in coroutine contexts for stateful operations, see Context Management. For details on the event system and observability, see Event System. For information about how commands are transformed for Laravel compatibility, see RedisConnection.


Overview

The Redis class (src/Redis.php17-142) serves as the primary interface for executing Redis commands. It acts as a proxy that:

  1. Obtains connections from the connection pool or coroutine context
  2. Delegates command execution to RedisConnection instances
  3. Dispatches events for observability
  4. Manages connection lifecycle based on command type

All Redis commands are executed through the magic __call method, which intercepts method calls and routes them to the underlying Redis connection.

Sources: src/Redis.php1-143


Command Execution Flow

The following diagram illustrates the complete execution flow for a Redis command, from invocation to result return:


Sources: src/Redis.php26-77


Connection Acquisition

The Redis client obtains connections through a two-tier strategy:

Context Check

The client first checks if a connection already exists in the coroutine context (src/Redis.php28):

Context::has($this->getContextKey())

The context key is formatted as redis.connection.{poolName} (src/Redis.php128-131).

Connection Source Priority

PrioritySourceConditionMethod
1Coroutine ContextConnection exists in contextContext::get($this->getContextKey())
2Connection PoolNo context connection$this->factory->getPool($this->poolName)->get()

Sources: src/Redis.php106-123

Connection Initialization

Once obtained, the connection is configured for transformation mode:

$connection->shouldTransform(true)

This enables Laravel-compatible command transformations. See Transformation System for details on transformation behavior.

Sources: src/Redis.php109-123


Command Invocation Pattern

The __call magic method (src/Redis.php26-77) handles all Redis command invocations. The general pattern is:


Execution Steps

  1. Timing Start: Record start time for performance tracking (src/Redis.php31)
  2. Connection Retrieval: Unwrap pool connection to RedisConnection instance (src/Redis.php37)
  3. Command Execution: Invoke method on connection with spread arguments (src/Redis.php38)
  4. Exception Capture: Catch any Throwable for event dispatch (src/Redis.php39-40)
  5. Performance Tracking: Calculate execution time in milliseconds (src/Redis.php42)
  6. Event Dispatch: Fire CommandExecuted event with metrics (src/Redis.php43-53)

Sources: src/Redis.php26-77


Result Handling

Normal Command Execution

For standard commands, the result flows directly from the Redis server through RedisConnection transformations back to the caller:

$result = $connection->{$name}(...$arguments);

The transformation layer in RedisConnection may modify the result to match Laravel conventions. For example:

  • get() returns null instead of false for missing keys
  • mget() maps false values to null
  • Hash operations return indexed arrays instead of associative arrays

See Command Transformations for complete transformation details.

Exception Handling

Exceptions are captured during execution (src/Redis.php39-40) but still dispatched to the event system (src/Redis.php43-53) before being re-thrown (src/Redis.php72-74):


This ensures observability even for failed commands.

Sources: src/Redis.php31-77


Connection Lifecycle

The connection lifecycle depends on whether the command requires stateful context:

Release Decision Matrix

ConditionActionRationale
Connection already in contextDo nothingReuse for subsequent commands
Command is multi, pipeline, or selectStore in context + defer cleanupStateful operation requires same connection
Database switched via selectUpdate connection database propertyTrack selected database
Standard commandImmediate releaseReturn to pool for other coroutines

Sources: src/Redis.php55-69

Stateful Commands

Three commands trigger connection retention (src/Redis.php97-104):

protected function shouldUseSameConnection(string $methodName): bool
{
 return in_array($methodName, [
 'multi', // Transaction block
 'pipeline', // Pipeline mode
 'select', // Database selection
 ]);
}

When these commands execute successfully:

  1. Connection is stored in coroutine context (src/Redis.php62)
  2. Database selection is tracked (src/Redis.php59-61)
  3. Cleanup is deferred to coroutine completion (src/Redis.php63-65)

Deferred Cleanup

The defer() function schedules connection release when the coroutine completes:

defer(function () {
 $this->releaseContextConnection();
});

The releaseContextConnection() method (src/Redis.php82-91) removes the connection from context and returns it to the pool.

Sources: src/Redis.php55-91 src/Redis.php97-104


Named Connections

The connection() method (src/Redis.php136-141) provides access to named Redis connection pools:


Usage Pattern

// Get default connection
$default = $redis->connection();
$default = $redis->connection('default');

// Get named connection
$cache = $redis->connection('cache');
$session = $redis->connection('session');

Each named connection returns a RedisProxy instance configured for that specific pool. See Redis Factory for more details on multi-pool configuration.

Sources: src/Redis.php136-141


Event Dispatch

Every command execution triggers a CommandExecuted event (src/Redis.php43-53):

Event Properties

PropertyTypeDescriptionSource
$namestringCommand name (e.g., "get", "set")Method name
$argumentsarrayCommand argumentsMethod arguments
$timefloatExecution time in millisecondsCalculated
$connectionRedisConnectionConnection instanceCurrent connection
$poolNamestringPool name (e.g., "default")Pool configuration
$resultmixedCommand resultExecution result
$exception?ThrowableException if failedCaught exception

This provides complete observability for debugging, monitoring, and logging. See Event System for details on consuming these events.

Sources: src/Redis.php43-53


Summary

The Redis client provides a clean interface for Redis operations through:

  1. Automatic connection management with context-aware pooling
  2. Magic method delegation for any Redis command
  3. Stateful operation support for transactions and pipelines
  4. Complete observability through event dispatch
  5. Named connection support for multi-pool architectures

The client handles the complexity of connection lifecycle, allowing application code to focus on business logic while maintaining high performance through connection pooling and coroutine context optimization.

Sources: src/Redis.php1-143