PHP code example of damimpr / cache-multi-layer

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

    

damimpr / cache-multi-layer example snippets



use CacheMultiLayer\Enum\CacheEnum;
use CacheMultiLayer\Service\Cache;

/*
 * creates the redis instance located on the host “redis-server” 
 * with a default TTL of 60 seconds 
 */ 
$cache = Cache::factory(CacheEnum::REDIS, 60, ['server_address' => 'redis-server']);


// set new value
$x = 8;
$key = 'test_key';
$res = $cache->set($key, $x);

// get
$y = $cache->get($key); // the value of $y is 8



//test with object

$foo = new Foo(); //Foo implements Cacheable
$foo->x = 5;
$keyFoo = 'key_foo';
$resFoo = $cache->set($keyFoo, $foo);
$fooCache = $cache->get($keyFoo);

$testEqual = $keyFoo === $foo; //$testEquals could be false
$testEqualX = $keyFoo->x === $foo->x; //testEqualX is true

use CacheMultiLayer\Enum\CacheEnum;
use CacheMultiLayer\Service\Cache;
use CacheMultiLayer\Service\CacheConfiguration;
use CacheMultiLayer\Service\CacheManager;

/*
 * creates the apcu instance as the highest priority cache and then
 * creates the redis instance located on the host ‘redis-server’ with a default TTL of 60 seconds with lower priority
 */
$cacheManager = CacheManager::factory();
$cacheManager->appendCache(Cache::factory(CacheEnum::APCU, 10));
$cacheManager->appendCache(Cache::factory(CacheEnum::REDIS, 65, ['server_address' => 'redis-server']));


// it's the same using cache configuration
 
$cacheConfiguration = new CacheConfiguration();
$cacheConfiguration->appendCacheLevel(CacheEnum::APCU, 10);
$cacheConfiguration->appendCacheLevel(CacheEnum::REDIS, 65, ['server_address' => 'redis-server']);
$cacheManager = CacheManager::factory($cacheConfiguration);


// set new value
$x = 8;
$key = 'test_key';
$res = $cacheManager->set($key, $x);

//wait 15 seconds
sleep(15); 


$y = $cacheManager->get($key); 
// the value of $y is 8 read from redis, and apcu, which had expired, has been refreshed
bash
  bash commands rector # Run powerful php tool useful for refactoring