FlushByPattern
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
Execute the pattern flush operation.
Details
at line 62
__construct(RedisConnection $connection)
Create a new pattern flush instance.
at line 74
int
execute(string $pattern)
Execute the pattern flush operation.