PHP code example of migears / cache

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

    

migears / cache example snippets


use MiGears\Cache\ArrayCache;
use Psr\Log\NullLogger;

$cache = new ArrayCache(new NullLogger());

$cache->set('key', 'value');
$value = $cache->get('key');       // 'value'
$cache->has('key');                // true
$cache->delete('key');
$cache->clear();

use MiGears\Cache\RedisCache;
use Psr\Log\NullLogger;

$redis = new Redis();
$redis->connect('127.0.0.1', 6379);

$cache = new RedisCache($redis, new NullLogger());

$rest->set(Redis::class, function () {
    $redis = new Redis();
    $redis->connect('127.0.0.1', 6379);
    return $redis;
});
// in a resource:
$cache = new RedisCache($this->resolve(Redis::class), new NullLogger());

$cache = new RedisCache($redis, new NullLogger(), allowedClasses: false);

$value = $cache->getOrSet('user_profile_42', function () use ($userId) {
    return $this->db->fetchUser($userId);  // expensive operation
}, 3600); // TTL optional

$appCache = $cache->withPrefix('myapp:');

$appCache->set('user', 'alice');   // stores as "myapp:user"
$appCache->get('user');            // returns "alice"
$appCache->clear();                // only clears keys starting with "myapp:"

use MiGears\Cache\ArrayCache;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

$logger = new Logger('cache');
$logger->pushHandler(new StreamHandler('cache.log'));

$cache = new ArrayCache($logger);

use MiGears\Cache\ArrayCache;
use Psr\Log\NullLogger;

$cache = new ArrayCache(new NullLogger());

$cache->set('key', 'value');
$value = $cache->get('key');       // 'value'
$cache->has('key');                // true
$cache->delete('key');
$cache->clear();

use MiGears\Cache\RedisCache;
use Psr\Log\NullLogger;

$redis = new Redis();
$redis->connect('127.0.0.1', 6379);

$cache = new RedisCache($redis, new NullLogger());

$rest->set(Redis::class, function () {
    $redis = new Redis();
    $redis->connect('127.0.0.1', 6379);
    return $redis;
});
// 在资源类中:
$cache = new RedisCache($this->resolve(Redis::class), new NullLogger());

$cache = new RedisCache($redis, new NullLogger(), allowedClasses: false);

$value = $cache->getOrSet('user_profile_42', function () use ($userId) {
    return $this->db->fetchUser($userId);  // 耗时操作
}, 3600); // TTL 可选

$appCache = $cache->withPrefix('myapp:');

$appCache->set('user', 'alice');   // 实际存储为 "myapp:user"
$appCache->get('user');            // 返回 "alice"
$appCache->clear();                // 只清除以 "myapp:" 开头的键

use MiGears\Cache\ArrayCache;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

$logger = new Logger('cache');
$logger->pushHandler(new StreamHandler('cache.log'));

$cache = new ArrayCache($logger);