seanja / cacheable-trait
简单的通用可缓存特性
1.0.1
2024-03-30 23:09 UTC
Requires
- php: ^8.3
- psr/cache: ^3.0
Requires (Dev)
- mockery/mockery: ^1.5
- phpunit/phpunit: ^10.0
- symfony/cache: *
Suggests
- symfony/cache: psr-6 cache implementation
This package is auto-updated.
Last update: 2024-10-01 00:25:58 UTC
README
简单的可配置特性,用于为每个方法添加缓存。
如何使用它
添加use并传入psr6缓存项池接口
class Controller { use SeanJA\Cache\CacheableTrait; public function __construct(CacheItemPoolInterface $cache) { $this->setCache($cache); } }
在方法中使用它
默认情况下,此值将被记住1小时
public function cacheableMethod( $cacheable_parameters ) { $data = $this->remember(function(){ return 'Cacheable data'; }); return response($data); }
配置TTL(每类)
在您的类中添加一个名为getTTL
的保护方法,该方法根据输入返回自定义日期间隔
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'; }
为缓存添加自定义ID(每类)
为缓存添加自定义值,可用于在部署时清除缓存,或者您可以手动设置在任意时刻清除缓存
protected function getCacheId(): string { return $_ENV['RELEASE_VERSION']; }
决定是否应该缓存某些内容(每类)
可用于避免缓存某些方法调用
protected function shouldCache(string $method, array $args): bool { return $method === 'maybeCache', $args[0] === 'plz cache'; }
禁用缓存(remember现在将不起作用,因为缓存为null)
这将禁用类的缓存,直到您恢复它
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; } }