sfneal / caching
用于利用缓存机制存储频繁检索数据的特性与接口。
4.1.0
2024-05-22 19:56 UTC
Requires
- php: ^8.0|^8.1|^8.2|^8.3
- laravel/framework: ^8.75|^9.0|^10.0|^11.0
- sfneal/redis-helpers: ^1.4|^2.0|^3.0
Requires (Dev)
- josiasmontag/laravel-redis-mock: >=1.2.6
- orchestra/testbench: ^7.40|^8.0|9.0
- phpunit/phpunit: ^9.6|^10.0|^11.0
- scrutinizer/ocular: ^1.8
- sfneal/currency: ^2.0
README
用于在Laravel应用程序中利用缓存机制存储频繁检索数据的特性与接口。
安装
您可以通过composer安装此包
composer require sfneal/caching
用法
1. 将缓存添加到Eloquent查询
在一个新的应用程序实例中(或自刷新缓存以来第一次调用)对(new CountUnreadInquiriesQuery())>fetch(600)
的第一次调用时,execute方法的输出将被存储在Redis缓存中,有效期为5分钟(600秒)。
如果在接下来的5分钟内再次调用(new CountUnreadInquiriesQuery())>fetch(600)
,则将从Redis缓存中检索之前的结果,无需执行完整的数据库查询。在这个例子中,节省的时间很少,但随着查询复杂性的增加,节省的时间会越来越多。
# Importing an example model that extends Sfneal/Models/AbstractModels use App\Models\Inquiry; # Import Cacheable trait that stores the output of the execute method in a Redis cache using the cacheKey method to set # the key. Any serializable output from execute can be stored, in this case we're simply storing an integer use Sfneal\Caching\Traits\Cacheable; # Importing AbstractQuery as we're building an Eloquent query cache use Sfneal\Queries\AbstractQuery; class CountUnreadInquiriesQuery extends AbstractQuery { use Cacheable; /** * Retrieve the number of unread Inquiries. * * @return int */ public function execute(): int { return Inquiry::query()->whereUnread()->count(); } /** * Retrieve the Queries cache key. * * @return string */ public function cacheKey(): string { # using AbstractModel::getTableName() to dynamically retrievethetable name to set the cache prefix return Inquiry::getTableName().':unread:count'; } }
测试
composer test
变更日志
请参阅CHANGELOG了解最近更改的更多信息。
贡献
请参阅CONTRIBUTING以获取详细信息。
安全
如果您发现任何安全相关的问题,请通过电子邮件stephen.neal14@gmail.com而不是使用问题跟踪器。
鸣谢
许可证
MIT许可证(MIT)。请参阅许可证文件以获取更多信息。
PHP包模板
此包是使用PHP包模板生成的。