mazz / global-static-cache-manager
PHP的全局静态缓存管理器
1.1.2
2021-02-02 14:19 UTC
Requires
- php: >=5.3.0
- psr/container: ^1.0@dev
- psr/simple-cache: ^1.0
Requires (Dev)
- phpunit/phpunit: ^8.0@dev
This package is auto-updated.
Last update: 2024-09-29 04:43:27 UTC
README
关于
在某些应用程序中,初始化一组数据并将其存储在静态变量中以供整个应用程序使用是非常有用的,而无需每次需要时都进行初始化。拥有大量的此类静态缓存变量可能导致代码质量下降。
Global-Static-Cache-Manager
引入了一个中央管理器来处理多个静态缓存。
StaticCacheContainer 使用 PSR-11 接口
StaticCache 使用 PSR-16 接口
安装
只需添加 composer 包
composer require mazz/php-global-static-cache-manager
使用方法
获取全局 StaticCacheContainer
的实例,并获取键为 currency_cache
的缓存。如果不存在此键的缓存,则会创建一个新的 StaticCache
并返回。
// Receive the Cache with the currency_cache $currencyCache = StaticCacheContainer::getInstance()->get('currency_cache'); // Fill the cache one by one $currencyCache->set(1, 'currency1'); $currencyCache->set(2, 'currency2'); $currencyCache->set(3, 'currency3'); // It is also possible to fill multiple at once $currencyCache->setMultiple([ 4 => 'currency4', 5 => 'currency5', ]);
然后您可以在应用程序的任何部分简单地访问缓存。
// Get the currency which is saved on index 4 $currency = StaticCacheContainer::getInstance()->get('currency_cache')->get(4); // it is also possible to set a default value $currency = StaticCacheContainer::getInstance()->get('currency_cache')->get(42, 'defaultCurrency'); // or load multiple keys at once $currency = StaticCacheContainer::getInstance()->get('currency_cache')->get([1,2,3);
您还可以检查缓存是否已初始化。如果您只想填充一次缓存,这将很有用。
// Returns true if cache with the key my_cache_key exists, false otherwise if(!StaticCacheContainer::getInstance()->has('my_cache_key')) { // you may want to fill the cache here }
StaticCache
还引入了其他有用的函数: has($key)
,clear()
,delete($key)
许可证
本项目是开源软件,受 MIT 许可证 许可。