becklyn / cache
提供简单(且快速)缓存的缓存包
1.1.0
2022-02-17 14:22 UTC
Requires
- php: >=7.4
- ext-json: *
- symfony/cache: ^5.4.3 || ^6.0.3
- symfony/config: ^5.4.3 || ^6.0.3
- symfony/dependency-injection: ^5.4.3 || ^6.0.3
- symfony/filesystem: ^5.4.3 || ^6.0.3
- symfony/framework-bundle: ^5.4.3 || ^6.0.3
- symfony/http-kernel: ^5.4.4 || ^6.0.4
Requires (Dev)
- roave/security-advisories: dev-master
- symfony/phpunit-bridge: ^5.4.3 || ^6.0.3
This package is auto-updated.
Last update: 2024-09-17 20:07:39 UTC
README
提供简单缓存,易于使用且性能高。警告:对于高度并发的使用,您应提前准备缓存或使用symfony自带的缓存,因为它具有适当的缓存雪崩保护。
使用方法
获取简单缓存工厂并获取缓存项
use Becklyn\Cache\Cache\SimpleCacheFactory; class MyService { private SimpleCacheItemInterface $cache; /** */ public function __construct (SimpleCacheFactory $cacheFactory) { $this->cache = $cacheFactory->getItem( "my.cache.key", fn () => $this->loadItems() ); } /** * Returns the cached or fresh items, depending on several conditions. */ public function getItems () : array { return $this->cache->get(); } /** * Loads the items from the database */ public function loadItems () : array { // ... } }
基于Symfony配置的缓存
您可以将缓存键和生成器传递给 getItem()
方法(如上面的示例所示),或者您可以额外传递需要跟踪和用于缓存失效的资源。
如果您传递资源,这将是一个两级缓存
- 第一级将是普通的 symfony/cache,它非常快,但没有适当的缓存失效方式。
- 第二级将是
ConfigCache
,如果跟踪的资源中的一些发生变化,它将自动失效。
$cacheFactory->getItem( "my.cache.key", fn () => $this->loadItems(), // eg. if your cache status depends on routing resources $this->router->getRouteCollection()->getResources() );