PHP code example of idct / php-rapid-cache-client

1. Go to this page and download the library: Download idct/php-rapid-cache-client library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

idct / php-rapid-cache-client example snippets




use IDCT\Cache\RapidCacheClient;

// host, port, optional key prefix
$cache = new RapidCacheClient('localhost', 6379, 'myapp:');

// Store any serializable value, optionally with a TTL (seconds or DateInterval)
$cache->set('user.123', ['name' => 'John Doe', 'roles' => ['admin']], 3600);

// Read it back (returns the supplied default on a miss)
$user = $cache->get('user.123', $default = null);

// Group entries under a tag, then invalidate the whole group at once
$cache->setTagged('user.123', $user, 'active-users');
$cache->clearByTag('active-users');

use IDCT\Cache\HashRapidCacheClient;

$hash = new HashRapidCacheClient('localhost', 6379, 'myapp:');

// Whole hash in one round-trip
$hash->set('user.123', ['name' => 'John Doe', 'visits' => 0, 'plan' => 'pro'], 3600);

// Single-field operations - no need to fetch the whole record
$plan = $hash->getField('user.123', 'plan');                  // HGET
$hash->setField('user.123', 'last_seen', '2026-05-28');       // HSET
$visits = $hash->incrementField('user.123', 'visits', 1);     // HINCRBY - atomic

use IDCT\Cache\RapidCacheClient;

$cache = new RapidCacheClient('localhost', 6379);

// A prefix is strongly recommended on a shared Redis instance - it namespaces
// every key and scopes clear() so it never deletes other apps' data.
$cache = new RapidCacheClient('localhost', 6379, 'myapp:');

use IDCT\Cache\RapidCacheClient;
use IDCT\Cache\RedisConnectionConfig;

$config = new RedisConnectionConfig(
    host: 'cache.internal',
    port: 6379,
    prefix: 'myapp:',
    password: 's3cr3t',      // null/empty → no AUTH
    database: 1,             // SELECT this DB (0 = none)
    connectTimeout: 1.0,     // seconds; phpredis default of 0 means "wait forever"
    readTimeout: 1.0,        // seconds; only applied when > 0
    persistent: true,        // reuse the connection across requests (pconnect)
    persistentId: 'pool1',   // pool id for persistent connections
    retryOnce: true,         // retry a failed op once on a transient RedisException
    pipelineBatchSize: 1000, // max commands per pipelined/multi-key batch
);

$cache = new RapidCacheClient($config);

// Store a value (returns bool)
$cache->set('user.123', ['name' => 'John Doe', 'email' => '[email protected]']);

// Retrieve a value ($default is returned only on a true miss)
$user = $cache->get('user.123');
$user = $cache->get('user.123', $defaultValue);

// Store with a TTL - int seconds or a DateInterval
$cache->set('session.abc', $sessionData, 3600);
$cache->set('session.abc', $sessionData, new DateInterval('PT1H'));

// Check existence (a fast probe - not a guarantee against a concurrent expiry)
if ($cache->has('user.123')) {
    // ...
}

// Delete a single key / clear the (prefix-scoped) cache
$cache->delete('user.123');
$cache->clear();

$cache->set('reset.token.abc', ['user_id' => 123]);

$payload = $cache->take('reset.token.abc');   // ['user_id' => 123], key is gone
$payload = $cache->take('reset.token.abc');   // null - nobody else can get it
$payload = $cache->take('missing', 'default');

// Store many at once (single MSET, or a pipelined SETEX batch when a TTL is given)
$cache->setMultiple(['k1' => 'v1', 'k2' => 'v2'], 60);

// Read many at once (single MGET); missing keys map to the default
$values = $cache->getMultiple(['k1', 'k2', 'k3'], 'fallback');

// Delete many at once (with tag cleanup per key)
$cache->deleteMultiple(['k1', 'k2']);

// Store and tag in one atomic call (optionally with a TTL)
$cache->setTagged('user.123', $userData, 'active-users');
$cache->setTagged('user.456', $otherUser, 'active-users', 3600);

// Or set first, tag later (the key must already exist)
$cache->set('post.789', $postData);
$cache->tag('post.789', 'posts');

// Iterate every value currently under a tag (key => value)
foreach ($cache->getTagged('active-users') as $key => $value) {
    echo "$key => " . json_encode($value) . PHP_EOL;
}

// Remove a single tag association (the value itself is kept)
$cache->untag('user.123', 'active-users');

// Count, then bulk-invalidate everything under a tag
$count = $cache->getTagCardinality('active-users');
$cache->clearByTag('active-users');

// Append items to the tail
$cache->enqueue('email-queue', ['to' => '[email protected]', 'subject' => 'Welcome']);
$cache->enqueue('email-queue', ['to' => '[email protected]', 'subject' => 'New user']);

// Pop items from the head (FIFO). Returns null when empty.
while ($email = $cache->pop('email-queue')) {
    echo 'Sending to: ' . $email['to'] . PHP_EOL;
}

// Pop several at once
$batch = $cache->pop('email-queue', 10);   // array of up to 10 items, or null

// Inspect without removing
$next  = $cache->peek('email-queue');       // head item, or null
$firstFive = $cache->peek('email-queue', 5);

// Length, or the full contents (head-first; O(N))
$length = $cache->getQueueLength('email-queue');
$all    = $cache->getQueue('email-queue');

// Replace the whole set with an exact membership (DEL + SADD)
$cache->createSet('user-roles:123', ['admin', 'editor', 'viewer']);

// Incremental changes
$cache->addToSet('user-roles:123', 'moderator');
$cache->removeFromSet('user-roles:123', 'viewer');

// Read all members (null when the set does not exist)
$roles = $cache->getSet('user-roles:123');

// Member count
$count = $cache->getCardinality('user-roles:123');

// Top 10 of a leaderboard (highest score first), as member => cachedValue
foreach ($cache->getSorted('leaderboard', count: 10, offset: 0, reversed: true) as $member => $value) {
    echo "$member => " . json_encode($value) . PHP_EOL;
}

// Count of a sorted set (pass true so ZCARD is used instead of SCARD)
$players = $cache->getCardinality('leaderboard', sortedSet: true);

$cache->set('page-views', 0);
$cache->increase('page-views', 1);
$cache->decrease('page-views', 1);

$views = $cache->get('page-views');

use IDCT\Cache\HashRapidCacheClient;

$hash = new HashRapidCacheClient('localhost', 6379, 'myapp:');

// PSR-16 surface works as expected; values must be a non-empty flat
// associative array of string/int/float scalars.
$hash->set('user.123', [
    'name'  => 'John Doe',
    'plan'  => 'pro',
    'score' => 1000,
], 3600);

// Whole-record read returns the hash as a flat array
$user = $hash->get('user.123');           // ['name' => 'John Doe', …]

$plan = $hash->getField('user.123', 'plan');                 // HGET
$hash->setField('user.123', 'last_seen', '2026-05-28');      // HSET
$hash->deleteField('user.123', 'score');                     // HDEL
if ($hash->hasField('user.123', 'plan')) { … }               // HEXISTS

// Read several fields at once
$slice = $hash->getFields('user.123', ['name', 'plan']);     // HMGET
//   ['name' => 'John Doe', 'plan' => 'pro']

// Merge fields into the existing record (does NOT clear unrelated fields)
$hash->setFields('user.123', ['score' => 2000, 'plan' => 'enterprise']);

// Remove several fields at once
$hash->deleteFields('user.123', ['score', 'last_seen']);     // HDEL …

$views = $hash->incrementField('page.views', 'count', 1);    // HINCRBY
$saved = $hash->incrementField('account.42', 'balance', 9.99); // HINCRBYFLOAT
$hash->decrementField('inventory.sku-7', 'stock', 1);

$hash->setTagged('user.123', $userRecord, 'active-users', 3600);
foreach ($hash->getTagged('active-users') as $key => $record) { … }
$hash->clearByTag('active-users');

use Psr\SimpleCache\InvalidArgumentException;
use Psr\SimpleCache\CacheException;

try {
    $cache->get('illegal:key');     // reserved character → InvalidArgumentException
} catch (InvalidArgumentException $e) {
    // bad input on our side
} catch (CacheException $e) {
    // the cache backend failed (the original RedisException is the chained cause)
}
bash
# Ubuntu/Debian
sudo apt-get install php-redis php-igbinary

# CentOS/RHEL
sudo yum install php-redis php-igbinary

# Or via PECL (answer "yes" to enable igbinary support when building redis)
pecl install redis igbinary
bash
composer analyse       # PHPStan (level 8)
composer fix           # php-cs-fixer (PSR-12 + Symfony rules)
composer test:mutation # Infection mutation testing
bash
   composer test      # unit + functional
   composer analyse   # PHPStan
   composer fix       # php-cs-fixer