PHP code example of yiisoft / cache-redis

1. Go to this page and download the library: Download yiisoft/cache-redis 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/ */

    

yiisoft / cache-redis example snippets


/**
 * @var \Predis\ClientInterface $client Predis client instance to use.
 */
$cache = new \Yiisoft\Cache\Redis\RedisCache($client);

$parameters = ['user_id' => 42];
$key = 'demo';

// try retrieving $data from cache
$data = $cache->get($key);

if ($data === null) {
    // $data is not found in cache, calculate it from scratch
    $data = calculateData($parameters);
    
    // store $data in cache for an hour so that it can be retrieved next time
    $cache->set($key, $data, 3600);
}

// $data is available here

$cache->delete($key);
// Or all cache
$cache->clear();

$client = new \Predis\Client([
        ['host' => 'redis-node-1', 'port' => 'redis-node-port-1',],
        ['host' => 'redis-node-2', 'port' => 'redis-node-port-2',],
        ['host' => 'redis-node-3', 'port' => 'redis-node-port-3',],
        ['host' => 'redis-node-4', 'port' => 'redis-node-port-4',],
        ['host' => 'redis-node-5', 'port' => 'redis-node-port-5',],
        ['host' => 'redis-node-6', 'port' => 'redis-node-port-6',],
    ],
    [
        'cluster' => 'redis',
        'parameters' => [
            'password' => 'Password',
        ],
    ]
);
$cache = new \Yiisoft\Cache\Redis\RedisCache($client);

$client = new \Predis\Client([
        ['host' => 'redis-node-1', 'port' => 'redis-node-port-1',],
        ['host' => 'redis-node-2', 'port' => 'redis-node-port-2',],
        ['host' => 'redis-node-3', 'port' => 'redis-node-port-3',],
        ['host' => 'redis-node-4', 'port' => 'redis-node-port-4',],
        ['host' => 'redis-node-5', 'port' => 'redis-node-port-5',],
        ['host' => 'redis-node-6', 'port' => 'redis-node-port-6',],
    ],
    [
        'cluster' => static function () {
            $distributor = new \CustomDistributor(); // Your custom distributor
            $strategy = new \Predis\Cluster\PredisStrategy($distributor);

            return new \Predis\Connection\Cluster\PredisCluster($strategy);
        },
        'parameters' => [
            'password' => 'Password',
        ],
    ]
);