PHP code example of talesoft / tale-cache-core

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

    

talesoft / tale-cache-core example snippets


use Tale\Cache\PoolCache;

$pool = new RedisCachePool(); //Create some PSR-6 CacheItemPool

$cache = new PoolCache($pool);
//$cache is now a PSR-16 cache

$data = $cache->get('some.key');
if ($data === null) {

    $data = ...; //Generate $data somehow
    $cache->set('some.key', $data);
}

//$data is now a cached value

use Psr\Cache\CacheItemPoolInterface;

final class MyService
{
    /** @var CacheItemPoolInterface */
    private $cachePool;
    
    public function __construct(CacheItemPoolInterface $cachePool)
    {
        $this->cachePool = $cachePool;
    }
    
    public function getCachePool(): CacheItemPoolInterface
    {
        return $this->cachePool;
    }
    
    public function doStuff(): void
    {
        $metadataItem = $this->cachePool->getItem('metadata');
        if (!$metadataItem->isHit()) {
            $metadataItem
                ->expiresAfter(new \DateInterval('P2D'))
                ->set($this->generateHeavyMetadata());
                
            $this->cachePool->save($metadataItem);
        }
        
        $metadata = $metadataItem->get();
        //Do something with $metadata
    }
}

use Tale\Cache\Pool\NullPool;

$myService = new MyService(new NullPool());

$myService->doStuff();

use Tale\Cache\Pool\RuntimePool;

$myService = new MyService(new RuntimePool());

$myService->doStuff();
$myService->doStuff(); //This will be faster, as values are cached during runtime

public function __construct(CacheItemPoolInterface $cachePool = null)
{
    $this->cachePool = $cachePool ?? new NullPool();
}

use Tale\Cache\Pool\AbstractPool;
use Tale\Cache\Item;

final class FilePool extends AbstractPool
{
    /** @var string */
    private $directory;
    
    public function __construct(string $directory)
    {
        $this->directory = $directory;
    }
    
    public function getItem($key): ItemInterface
    {
        $path = $this->getPathFromKey($key);
        if (file_exists($path)) {
        
            //Unserialize data from file
            [$ttl, $value] = unserialize(file_get_contents($path));
            
            //Check TTL
            if (time() < filemtime() + $ttl) {
            
                $expirationTime = new \DateTimeImmutable();
                $expirationTime->setTimestamp($expirationTime->getTimestamp() + $ttl);
                
                //Return a hit item
                return Item::createHit($key, $value, $expirationTime);
            }
        }
        //Create a miss
        return Item::createMiss($key);
    }

    public function clear(): bool
    {
        $files = glob("{$this->directory}/*.cache");
        $success = true;
        foreach ($files as $file) {
            if (!unlink($file)) {
                $success = false;
            }
        }
        return $success;
    }

    public function deleteItem($key): bool
    {
        $path = $this->getPathFromKey($key);
        return unlink($path);
    }

    public function save(CacheItemInterface $item): bool
    {
        //Make sure that it's an (interopable) Tale\Cache\ItemInterface instance
        //including items from this instance (which makes it downwards PSR-6 compatible)
        $this->filterItem($item);
        
        $path = $this->getPathFromKey($item->getKey());
        
        //This ->getExpireTime() call here is what enables interopability
        $ttl = time() - $item->getExpireTime()->getTimestamp();
        
        return file_put_contents($path, serialize([$ttl, $item->get()])) !== false;
    }
    
    private function getPathFromKey($key): string
    {
        $hash = md5($key);
        return "{$this->directory}/{$hash}.cache";
    }
}

$pool = new FilePool('/my/cache');

$item = $pool->getItem('my.data');
if (!$item->isHit()) {
    //Generate $data somehow
    $data = ...;
    
    $item
        ->expiresAfter(new \DateInterval('P2D'))
        ->set($data);
    $pool->saveDeferred($item);
}

$cachedData = $item->get();

//At end of execution
$pool->commit();

$poolA = new SomeCachePool();
$poolB = new SomeOtherCachePool();

$item = $poolA->getItem('some.item');
if ($item->isHit()) {
    $poolA->deleteItem($item);
    $poolB->save($item); //Cache Item has been moved to poolB
}