emileperron / magic-cache
一个易于使用的缓存库,底层使用 Symfony 的 FilesystemAdapter。
v1.1.2
2020-11-21 22:25 UTC
Requires
- php: >=7.2.5
- symfony/cache: ^5.1
This package is auto-updated.
Last update: 2024-09-13 10:34:25 UTC
README
MagicCache 是一个简单的缓存库,通过封装 Symfony 的 FilesystemAdapter 来提供最简单的缓存体验。
如果你有一个需要缓存的小项目,或者有一个具有非常简单缓存需求的大项目,这个库适合你。
这个库的亮点是 Cache::magicGet()
和 Cache::magicSet()
方法,允许你在不自己定义唯一缓存键的情况下从缓存中保存或检索数据。下面有更多关于这个的详细信息。
入门
要开始使用,只需通过 Composer 需求此包
composer require emileperron/magic-cache
完成后,你就可以在你的项目中开始使用这个库了。以下是关于库的用法和功能的简要概述
<?php use Emileperron\MagicCache\Cache; // Saving data to cache // Definition: set($key, $value, $expiresAfter = 0) Cache::set('my_cache_key', 'my value'); Cache::set('my_cache_key_2', 'my second value', 3600); Cache::set('my_cache_key_3', ['obj' => 'value']); // Getting data from cache // Definition: get($key, $fallback = null) Cache::get('my_cache_key'); Cache::get('my_non_existing_key', 'fallback value'); // The $fallback parameter also allows for callables Cache::get('my_non_existing_key', 'MyClass::myCallbackMethod'); Cache::get('my_non_existing_key', ['MyClass', 'myCallbackMethod']); Cache::get('my_non_existing_key', function(){ return 'fallback value'; }); // Manually removing data from cache // Definition: remove($key) Cache::remove('my_cache_key_3'); // Pruning the cache (deletes all expired cache entries) // Definition: prune() Cache::prune(); // This library defines two magic methods: magicGet() and magicSet() // These methods automatically generate a cache key based on the calling function's class, name and parameters. // Here's an example: function getRecordFromDatabase($id) { return Cache::magicGet([], function() use ($id) { $value = fetchValueFromDatabase($id); // replace this with your own data fetching/processing code return Cache::magicSet($value); }); } // The definition of both methods goes as follows: // magicGet($fallback = null, $suffixes = []) // magicSet($value, $expiresAfter = 0, $suffixes = [])
魔法 get()
和 set()
方法
这个库定义了两个魔法方法:magicGet()
和 magicSet()
。这些方法会自动根据调用函数的类、名称和参数生成缓存键。
这并不总是可用(例如:如果你在函数的参数中传递整个文件或数据流),但它适用于许多简单的用例,而这些用例实际上更为常见。
这两个方法都接受一个 $suffixes
参数,允许你以数组的形式传递自己的唯一标识符。然后,这些后缀将用于代替调用函数的参数。调用函数的类和名称仍将用于生成特定方法的唯一缓存键。
贡献
如果你想添加功能或对此库提出改进建议,请随时在 GitHub 仓库 提交 pull requests。我会尽快查看并合并它们。
如果你遇到问题但没有时间修复,你也可以提交问题。
支持
最后,如果你使用这个库并想支持我,以下是一些你可以做到的方式