PHP code example of thadafinser / psr6-null-cache

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

    

thadafinser / psr6-null-cache example snippets


namespace MyPackage;

use Psr\Cache\CacheItemPoolInterface;

class MyCode
{

    public function __construct(CacheItemPoolInterface $cache = null)
    {
        $this->cache = $cache;
    }

    /**
     * Can return an instance of null, which is bad!
     *
     * @return null CacheItemPoolInterface
     */
    public function getCache()
    {
        return $this->cache;
    }

    private function internalHeavyMethod()
    {
        $cacheKey = 'myKey';
        
        // you need to check first, if there is a cache instance around
        if ($this->getCache() !== null && $this->getCache()->hasItem($cacheKey) === true) {
            // cache is available + it has a cache hit!
            return $this->getCache()->getItem($cacheKey);
        }
        
        $result = do_something_heavy();
        
        // you need to check first, if there is a cache instance around
        if ($this->getCache() !== null) {
            $item = $this->getCache()->getItem($cacheKey);
            $item->set($result);
            $this->getCache()->save($item);
        }
        
        return $result;
    }
}


namespace MyPackage;

use Psr\Cache\CacheItemPoolInterface;
use Psr6NullCache\NullCacheItemPool;

class MyCode
{

    /**
     * You could  if($cache === null){
            $cache = new NullCacheItemPool();
        }
        
        $this->cache = $cache;
    }

    /**
     * @return CacheItemPoolInterface
     */
    public function getCache()
    {
        return $this->cache;
    }

    private function internalHeavyMethod()
    {
        $cacheKey = 'myKey';
        
        if ($this->getCache()->hasItem($cacheKey) === true) {
            // cache is available + it has a cache hit!
            return $this->getCache()->getItem($cacheKey);
        }
        
        $result = do_something_heavy();
        
        $item = $this->getCache()->getItem($cacheKey);
        $item->set($result);
        $this->getCache()->save($item);
        
        return $result;
    }
}