PHP code example of klsoft / yii2-cache-redis

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

    

klsoft / yii2-cache-redis example snippets


use Yii;
use yii\web\CacheSession;
use Klsoft\Yii2CacheRedis\RedisCache;

return [
    // ...
    'components' => [
        // ...
        'session' => [
            'class' => CacheSession::class,
            'cache' => new RedisCache(
                new Redis([
                    'host' => $params['redisHost'],
                    'port' => $params['redisPort'],
                    'database' => $params['redisDatabaseSession']
                ]))
        ],
        'cache' => new RedisCache(
            new Redis([
                'host' => $params['redisHost'],
                'port' => $params['redisPort'],
                'database' =>  $params['redisDatabaseCache']
            ]))
    ],
];

namespace MyNamespace;

use Yii;

final class ProductRepository implements ProductRepositoryInterface
{
    private int $cacheDuration;
    private const TOP_PRODUCTS = 'top_poroducts';

    public function __construct(int $cacheDuration)
    {
        $this->cacheDuration = $cacheDuration;
    }

    public function getTopProducts(int $numberOfTopProducts): array
    {
        return Yii::$app->cache->getOrSet(
            ProductRepository::TOP_PRODUCTS,
            function () use ($numberOfTopProducts) {
                return $this->getTopProductsFromDb($numberOfTopProducts);
            },
            $this->cacheDuration);
    }
}