trm42/cache-decorator

适用于Laravel 5的神奇(节省大量手动工作)缓存装饰器。专为与仓库一起使用而设计,但也很容易用于其他用途。如果有足够的兴趣,可以使其成为框架无关。

0.9.3 2016-04-29 19:54 UTC

This package is not auto-updated.

Last update: 2024-09-24 19:19:08 UTC


README

仓库是真正的好东西,它解决了现实世界的问题,并遵循了DRY(不要重复自己)的理念,但是为仓库缓存制作类似类,并重复编写像这样的代码

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;
	}

}

设置完毕!缓存装饰器会缓存除了$excludes数组之外的每个方法调用。

请注意,当前版本不支持将对象作为方法调用的一部分。它将在v1.0.0版本中添加。

如果你需要为某些方法进行特殊处理,你总是可以在Cached Repository类中覆盖它们,如下(简单示例)

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'];

设置完毕!

安装

使用composer安装

composer require trm42/cache-decorator

复制默认配置

cp vendor/trm42/cache-decorator/config/repository_cache.php ./config/

测试了Laravel 5.1和5.2。