PHP code example of yiisoft / cache

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

    

yiisoft / cache example snippets


$arrayCache = new \Yiisoft\Cache\ArrayCache();

$arrayCacheWithPrefix = new \Yiisoft\Cache\PrefixedCache(new \Yiisoft\Cache\ArrayCache(), 'myapp_');

$cache = new \Yiisoft\Cache\Cache($arrayCache);

$cache = new \Yiisoft\Cache\Cache($arrayCache, 60 * 60); // 1 hour

$cache = new \Yiisoft\Cache\ArrayCache();
$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();

$cache = new \Yiisoft\Cache\Cache(new \Yiisoft\Cache\ArrayCache());
$key = ['top-products', $count = 10];

$data = $cache->getOrSet($key, function (\Psr\SimpleCache\CacheInterface $cache) use ($count) {
    return getTopProductsFromDatabase($count);
}, 3600);

$cache->remove($key);

$value = $cache
    ->psr()
    ->get('myKey');

/**
 * @var callable $callable
 * @var \Yiisoft\Cache\CacheInterface $cache
 */

use Yiisoft\Cache\Dependency\TagDependency;

// Set multiple cache values marking both with a tag.
$cache->getOrSet('item_42_price', $callable, null, new TagDependency('item_42'));
$cache->getOrSet('item_42_total', $callable, 3600, new TagDependency('item_42'));

// Trigger invalidation by tag.
TagDependency::invalidate($cache, 'item_42');

/**
 * @var mixed $key
 * @var callable $callable
 * @var \DateInterval $ttl
 * @var \Yiisoft\Cache\CacheInterface $cache
 * @var \Yiisoft\Cache\Dependency\Dependency $dependency
 */

$beta = 2.0;
$cache->getOrSet($key, $callable, $ttl, $dependency, $beta);

use Yiisoft\Cache\Serializer\SerializerInterface;

final class IgbinarySerializer implements SerializerInterface 
{
    public function serialize(mixed $value) : string
    {
        return igbinary_serialize($value);
    }

    public function unserialize(string $data) : mixed
    {
        return igbinary_unserialize($data);
    }
}