PHP code example of trm42 / cache-decorator

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

    

trm42 / cache-decorator example snippets


namespace something\nice;

class CachedUserRepository {
	
	protected $repository;
	protected $cache;

	public function __construct(UserRepository $users, Cache $cache) {
		$this->repository = $users;
		$this->cache = $cache;
	}

	function all()
	{
		if (!$this->cache->has('all')) {
			$results = $this->repository->all();
			$this->cache->save('all', $results);
		} else {
			$results = $this->cache->get('all');
		}

		return $results;

	}

	function findByX($x)
	{
		$key = 'find-' . $x;
		if (!$this->cache->has($key)) {
			$results = $this->repository->findByX($x);
			$this->cache->save($key, $results);
		} else {
			$results = $this->cache->get($key);
		}

		return $results;
	}
}

namespace My\Repositories;

use Trm42\CacheDecorator\CacheDecorator;

class CachedUserRepository extends CacheDecorator {
	
	protected $ttl = 5; // cache ttl in minutes
	protected $prefix_key = 'users';
	protected $excludes = ['all']; // these methods are not cached

	public function repository()
	{
		return UserRepository::class;
	}

}


public function findByX($x)
{

	$key = $this->generateCacheKey(__FUNCTION__, compact($x));

	$res = $this->getCache($key);

	if (!$res) {
		$results = $this->repository->findX($x);
		
		$this->putCache($key, $results);
	}

	return $res;

}

// Additional properties to add to the earlier example
// with class decoration
protected $tag_cleaners = ['create'];
protected $tags = ['users'];
bash
cp vendor/trm42/cache-decorator/config/repository_cache.php ./config/