final class FlushByPattern

Flush (delete) Redis keys matching a pattern.

This class uses SafeScan to iterate keys efficiently and deletes them in batches. It correctly handles OPT_PREFIX to avoid the double-prefixing bug.

Why This Exists

Pattern-based key deletion is needed for cleanup operations (tests, benchmarks, cache invalidation by prefix). However, phpredis OPT_PREFIX makes this tricky:

  • SCAN doesn't auto-add OPT_PREFIX to patterns
  • SCAN returns keys WITH the full prefix as stored
  • DEL auto-adds OPT_PREFIX to key names

Without SafeScan, you'd try to delete "prefix:prefix:key" instead of "prefix:key".

Usage

Typically used through the Redis proxy:

// Via Redis facade (handles connection lifecycle)
Redis::flushByPattern('cache:users:*');

// Direct connection use requires raw phpredis results
$redis->withConnection(
    fn (RedisConnection $connection) => $connection->flushByPattern('cache:users:*'),
    transform: false,
);

Warning

When used with cache, this bypasses tag management. Only use for:

  • Non-tagged items
  • Administrative cleanup where orphaned tag references are acceptable
  • Test/benchmark data cleanup

Constants

private BUFFER_SIZE

Number of keys to buffer before executing a batch delete.

Balances memory usage vs. number of Redis round-trips.

Methods

__construct(RedisConnection $connection)

Create a new pattern flush instance.

int
execute(string $pattern)

Execute the pattern flush operation.

Details

at line 62
__construct(RedisConnection $connection)

Create a new pattern flush instance.

Parameters

RedisConnection $connection

A held raw Redis connection (not released until done)

at line 74
int execute(string $pattern)

Execute the pattern flush operation.

Parameters

string $pattern

The pattern to match (e.g., "cache:test:*"). Should NOT include OPT_PREFIX - it's handled automatically.

Return Value

int

Number of keys deleted