PHP code example of asm89 / twig-cache-extension

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

    

asm89 / twig-cache-extension example snippets




use Doctrine\Common\Cache\ArrayCache;
use Asm89\Twig\CacheExtension\CacheProvider\DoctrineCacheAdapter;
use Asm89\Twig\CacheExtension\CacheStrategy\LifetimeCacheStrategy;
use Asm89\Twig\CacheExtension\Extension as CacheExtension;

$cacheProvider  = new DoctrineCacheAdapter(new ArrayCache());
$cacheStrategy  = new LifetimeCacheStrategy($cacheProvider);
$cacheExtension = new CacheExtension($cacheStrategy);

$twig->addExtension($cacheExtension);



use Asm89\Twig\CacheExtension\CacheProvider\PsrCacheAdapter;
use Asm89\Twig\CacheExtension\CacheStrategy\LifetimeCacheStrategy;
use Asm89\Twig\CacheExtension\Extension as CacheExtension;
use Cache\Adapter\Apcu\ApcuCachePool;

$cacheProvider  = new PsrCacheAdapter(new ApcuCachePool());
$cacheStrategy  = new LifetimeCacheStrategy($cacheProvider);
$cacheExtension = new CacheExtension($cacheStrategy);

$twig->addExtension($cacheExtension);



use Asm89\Twig\CacheExtension\CacheStrategy\KeyGeneratorInterface;

class MyKeyGenerator implements KeyGeneratorInterface
{
    public function generateKey($value)
    {
        return get_class($value) . '_' . $value->getId() . '_' . $value->getUpdatedAt();
    }

}



use Asm89\Twig\CacheExtension\CacheStrategy\GenerationalCacheStrategy;
use Asm89\Twig\CacheExtension\Extension as CacheExtension;

$keyGenerator   = new MyKeyGenerator();
$cacheProvider  = /* see Quick start */;
$cacheStrategy  = new GenerationalCacheStrategy($cacheProvider, $keyGenerator, 0 /* = infinite lifetime */);
$cacheExtension = new CacheExtension($cacheStrategy);

$twig->addExtension($cacheExtension);



use Asm89\Twig\CacheExtension\CacheStrategy\IndexedChainingCacheStrategy;
use Asm89\Twig\CacheExtension\Extension as CacheExtension;

$cacheStrategy  = new IndexedChainingCacheStrategy(array(
    'time' => $lifetimeCacheStrategy,
    'gen'  => $generationalCacheStrategy,
));
$cacheExtension = new CacheExtension($cacheStrategy);

$twig->addExtension($cacheExtension);