PHP code example of seanja / cacheable-trait

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

    

seanja / cacheable-trait example snippets


class Controller
{
    use SeanJA\Cache\CacheableTrait;
    
    public function __construct(CacheItemPoolInterface $cache)
    {
      $this->setCache($cache);
    }
}

    public function cacheableMethod( $cacheable_parameters )
    {
        $data = $this->remember(function(){
            return 'Cacheable data';
        });

        return response($data);
    }

    protected function getTTL(string $method, array $args): DateInterval
    {
        return match ($method) {
            'method1' => DateInterval::createFromDateString('1 day'),
            'method2' => DateInterval::createFromDateString('10 seconds'),
            'method3' => DateInterval::createFromDateString('10 seconds'),
            default => DateInterval::createFromDateString('6 minutes'),
        };
    }

    protected function generateCacheKey(string $class, string $method, array $args): string
    {
        return 'key';
    }

    protected function getCacheId(): string
    {
        return $_ENV['RELEASE_VERSION'];
    }

    protected function shouldCache(string $method, array $args): bool
    {
        return $method === 'maybeCache', $args[0] === 'plz cache';
    }

    public function shouldDisableCaching(): void
    {
        $this->disableCache();
    }

class CachedClass{
    use \SeanJA\Cache\CacheableTrait;
    
    public function cachedTime(){
        return $this->remember(function(){
            return time();
        });
    }

    public function uncachedTime(): void
    {
        $this->disableCache();
        $data = $this->cachedTime();
        $this->restoreCache();
        return $data; 
    }
}