mostafaznv/laracache
Composer 安装命令:
composer require mostafaznv/laracache
包简介
LaraCache is a customizable cache trait to cache queries on model's events
README 文档
README
Using this package, you can cache your heavy and most used queries.
All you have to do is to define the CacheEntity objects in the model and specify a valid name and ttl for them.
LaraCache will handle the rest of process automatically. It will create and update cache entities based on ttl that you've defined for each entity.
Manually updating the cache entities of models after dispatching model events (creating, updating and deleting) isn't required, LaraCache manages them in the background and ensures the most up-to-date version of each cache entity.
In addition to the core LaraCache package, I have developed a complementary package called Nova LaraCache. Nova LaraCache seamlessly integrates LaraCache with Laravel Nova, the administration panel for Laravel applications. It offers a user-friendly interface within the Laravel Nova administration panel, enabling users to conveniently moderate and manage cache entities.
I am on an open-source journey 🚀, and I wish I could solely focus on my development path without worrying about my financial situation. However, as life is not perfect, I have to consider other factors.
Therefore, if you decide to use my packages, please kindly consider making a donation. Any amount, no matter how small, goes a long way and is greatly appreciated. 🍺
Requirements:
- PHP 8.3 or higher
- Laravel 12 or higher
To install LaraCache on older Laravel/PHP versions, consult the compatibility table below to determine which LaraCache release to use:
| Laravel Version | PHP Version | LaraCache Version |
|---|---|---|
| 8.40.0 — 12.x | 8.0.2 — 8.5 | 2.5.2 |
| 12.x | 8.3 or higher | master (3.x) |
Installation
-
Install the package via composer:
composer require mostafaznv/laracache
-
Publish config file:
php artisan vendor:publish --provider="Mostafaznv\LaraCache\LaraCacheServiceProvider" -
Done
Usage
-
Add LaraCache trait to the model
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Mostafaznv\LaraCache\Traits\LaraCache; class Article extends Model { use LaraCache; /** * Define Cache Entities Entities * * @return CacheEntity[] */ public static function cacheEntities(): array { return [ CacheEntity::make('list.forever') ->cache(function() { return Article::query()->latest()->get(); }), CacheEntity::make('latest') ->validForRestOfDay() ->cache(function() { return Article::query()->latest()->first(); }) ]; } }
-
Retrieve Cache
use App\Models\Article; use Mostafaznv\LaraCache\Facades\LaraCache; $cache = Article::cache()->get('latest'); // or $cache = LaraCache::retrieve(Article::class, 'latest');
Table of Contents:
- Installation
- Usage
- CacheEntity Methods
- Disable/Enable Cache
- Update Cache Manually
- Delete Cache Manually
- Artisan Commands
- Laravel Nova Support
- Config Properties
- Complete Example
CacheEntity Methods
| method | Arguments | description |
|---|---|---|
| setDriver | driver (type: string) |
Specifies custom driver for cache entity |
| isQueueable | status (type: bool, default: 'true')onConnection (type: string, default: '')onQueue (type: string, default: '') |
This option specifies whether the cache operation should be performed in the background or not. Note: By using the onConnection and onQueue arguments, you have the ability to specify custom connection and queue names for each cache entity. |
| debounce | status (type: bool, default: 'true')waitTime (type: int, default: 5)onConnection (type: string, default: '')onQueue (type: string, default: '') |
This option specifies whether the cache operation should be debounced or not. Note: To use the debouncing mechanism, a proper queue system must be configured and running. |
| refreshAfterCreate | status (type: bool, default: true) |
Specifies if the cache should refresh after create a record |
| refreshAfterUpdate | status (type: bool, default: true) |
Specifies if the cache should refresh after update a record |
| refreshAfterDelete | status (type: bool, default: true) |
Specifies if the cache should refresh after delete a record |
| refreshAfterRestore | status (type: bool, default: true) |
Specifies if the cache should refresh after restore a record |
| forever | Specifies that the cache should be valid forever | |
| validForRestOfDay | Specify that cache entity should be valid till end of day | |
| validForRestOfWeek | Specify that cache entity should be valid till end of week | |
| ttl | seconds (type: int) |
Specifies cache time to live in second |
| setDefault | defaultValue (type: mixed) |
Specifies default value for the case that cache entity doesn't have any value |
| cache | Closure | Main part of each cache entity. defines cache content |
Disable/Enable Cache
If you want to disable/enable cache, you can do it in the following two ways:
Disable
use App\Models\Article; use Mostafaznv\LaraCache\Facades\LaraCache; Article::cache()->disable(); // or LaraCache::disable(Article::class);
Enable
use App\Models\Article; use Mostafaznv\LaraCache\Facades\LaraCache; Article::cache()->enable(); // or LaraCache::enable(Article::class);
Update Cache Manually
Sometimes you want to update cache entities manually.
Update an Entity
use App\Models\Article; use Mostafaznv\LaraCache\Facades\LaraCache; Article::cache()->update('latest'); // or LaraCache::update(Article::class, 'latest');
Update all Entities
use App\Models\Article; use Mostafaznv\LaraCache\Facades\LaraCache; Article::cache()->updateAll(); // or LaraCache::updateAll(Article::class);
Update all LaraCache Entities
This will update all cache entities that stored using LaraCache (across all models)
use App\Models\Article; use Mostafaznv\LaraCache\Facades\LaraCache; LaraCache::updateAll();
Delete Cache Manually
Sometimes you want to delete cache entities manually. using these methods, you can do it.
Delete an Entity
Using this feature, you can delete cache entities temporary. after spending ttl, cache entity will be generated again.
use App\Models\Article; use Mostafaznv\LaraCache\Facades\LaraCache; Article::cache()->delete('latest'); // or LaraCache::delete(Article::class, 'latest');
Delete an Entity Forever
Using this feature, you can delete cache entities permanently. Cache item will be deleted forever and whenever you try to retrieve it, you will get null (or default value).
use App\Models\Article; use Mostafaznv\LaraCache\Facades\LaraCache; Article::cache()->delete('latest', true); // or LaraCache::delete(Article::class, 'latest', true);
Note: Cache Entity will update after creating or updating records in your model
Delete all Model Entities
use App\Models\Article; use Mostafaznv\LaraCache\Facades\LaraCache; Article::cache()->deleteAll(); // or LaraCache::deleteAll(Article::class);
Delete all Model Entities Forever
use App\Models\Article; use Mostafaznv\LaraCache\Facades\LaraCache; Article::cache()->deleteAll(true); // or LaraCache::deleteAll(Article::class, true);
Delete all LaraCache Entities
This will delete all cache entities that stored using LaraCache (across all models)
use App\Models\Article; use Mostafaznv\LaraCache\Facades\LaraCache; LaraCache::deleteAll(); // forever LaraCache::deleteAll(forever: true);
Artisan Commands
This feature allows you to update or delete multiple cache entities of one or more models from the console command. This means you can programmatically control the cache data outside the caching cycle.
You can also create groups of models and their entities in the config file and easily update or delete all their entities at once.
Update Cache
# updates all entities of article model php artisan laracache:update -m Article # updates specified entities of article model php artisan laracache:update -m Article -e latest -e featured # updates all entities of article and product models php artisan laracache:update -m Article -m Product # defines model with full namespace php artisan laracache:update -m "Domain\Article\Models\Article"
Delete Cache
# deletes all entities of article model php artisan laracache:delete -m Article # deletes specified entities of article model php artisan laracache:delete -m Article -e latest -e featured # deletes all entities of article and product models php artisan laracache:delete -m Article -m Product # defines model with full namespace php artisan laracache:delete -m "Domain\Article\Models\Article"
Note: If you don't specify any entity, all entities will be operated.
Note: If you specify multiple models, you can't specify any entity and all entities of all models will be operated.
Group Operations
# updates all entities of models that are in group-1 php artisan laracache:update-group group-1 # deletes all entities of models that are in group-1 php artisan laracache:delete-group group-1
This is an example of a group configuration:
# config/laracache.php return [ // ... 'groups' => [ 'group-1' => [ [ 'model' => \App\Models\User::class, 'entities' => [ 'users.latest', 'users.featured' ], ], [ 'model' => \App\Models\Article::class, 'entities' => [], ] ], 'group-2' => [ [ 'model' => \App\Models\Article::class, 'entities' => [ 'featured-list', 'latest' ], ], [ 'model' => \App\Models\User::class, 'entities' => ['users.latest'], ] ], ] ];
Laravel Nova Support
Nova LaraCache is a powerful Laravel Nova package that extends the functionalities of LaraCache by integrating it seamlessly with Laravel Nova. It provides an intuitive interface within the Laravel Nova administration panel, allowing users to effortlessly moderate and manage cache entities.
With Nova LaraCache, users can conveniently monitor cache expiration dates, review cache entity contents, regenerate cache items, and delete specific cache entries.
To unlock the cache management capabilities provided by Nova LaraCache, please refer to the installation instructions and consult the LaraCache documentation for guidance on creating cache entities for each model.
Config Properties
| method | Type | description |
|---|---|---|
| driver | string (default: null) |
The default mechanism for handling cache storage. If you keep this option null, LaraCache will use the default cache storage from config/cache.php |
| laracache-list | string (default: laracache.list) |
LaraCache uses a separate list to store name of all entities. using these keys, we can perform some actions to all entities (such as update or delete them) |
| first-day-of-week | integer (default: 0) |
In some regions, saturday is first day of the week and in another regions it may be different. you can change the first day of a week by changing this property |
| last-day-of-week | integer (default: 6) |
In some regions, friday is last day of the week and in another regions it may be different. you can change the last day of a week by changing this property |
| queue.status | bool (default: false) |
Sometimes caching process is very heavy, so you have to queue the process and do it in background. |
| queue.name | string (default: default) |
You have the option to set custom name for the queue process. This name will be used when invoking the onQueue method while dispatching the queue job. |
| queue.connection | string (default: null) |
You have the option to set custom connection for the queue process. This connection will be used when invoking the onConnection method while dispatching the queue job. |
| debounce.status | bool (default: false) |
In some scenarios, there may be many requests to regenerate a cache entity. This can cause laracache to query the database and update the corresponding cache entities too frequently. In such cases, enabling debouncing can be helpful. It collects multiple regeneration requests and only processes the most recent one. |
| debounce.wait | integer (default: 5) |
Defines the waiting time (in seconds) before processing a debounced cache regeneration request. By default, it is set to 5 seconds, meaning that if multiple requests arrive within this interval, only the most recent one will be executed after the wait period. |
| debounce.queue.name | string (default: default) |
You have the option to set custom name for the debounce process. This name will be used when invoking the onQueue method while dispatching the queue job. |
| debounce.queue.connection | string (default: null) |
You have the option to set custom connection for the debounce process. This connection will be used when invoking the onConnection method while dispatching the queue job. |
| groups | array (default: []) |
You can group some entities and perform some operations on them |
Complete Example
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Mostafaznv\LaraCache\Traits\LaraCache; class Article extends Model { use LaraCache; /** * Define Cache Entities Entities * * @return CacheEntity[] */ public static function cacheEntities(): array { return [ CacheEntity::make('list.forever') ->forever() ->setDriver('redis') ->cache(function() { return Article::query()->latest()->get(); }), CacheEntity::make('list.frequent') ->debounce() ->validForRestOfDay() ->cache(function() { return Article::query()->latest()->get(); }), CacheEntity::make('list.day') ->isQueueable() ->validForRestOfDay() ->cache(function() { return Article::query()->latest()->get(); }), CacheEntity::make('list.week') ->isQueueable(true, 'redis', 'low') ->validForRestOfWeek() ->cache(function() { return Article::query()->latest()->get(); }), CacheEntity::make('list.ttl') ->ttl(120) ->cache(function() { return Article::query()->latest()->get(); }), CacheEntity::make('latest') ->forever() ->cache(function() { return Article::query()->latest()->first(); }), CacheEntity::make('latest.no-create') ->refreshAfterCreate(false) ->cache(function() { return Article::query()->latest()->first(); }), CacheEntity::make('latest.no-update') ->refreshAfterUpdate(false) ->cache(function() { return Article::query()->latest()->first(); }), CacheEntity::make('latest.no-delete') ->refreshAfterDelete(false) ->cache(function() { return Article::query()->latest()->first(); }), CacheEntity::make('latest.no-restore') ->refreshAfterRestore(false) ->cache(function() { return Article::query()->latest()->first(); }), CacheEntity::make('empty.array') ->setDefault('empty value') ->cache(fn() => []), ]; } }
I am on an open-source journey 🚀, and I wish I could solely focus on my development path without worrying about my financial situation. However, as life is not perfect, I have to consider other factors.
Therefore, if you decide to use my packages, please kindly consider making a donation. Any amount, no matter how small, goes a long way and is greatly appreciated. 🍺
License
This software is released under The MIT License (MIT).
mostafaznv/laracache 适用场景与选型建议
mostafaznv/laracache 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 50.31k 次下载、GitHub Stars 达 272, 最近一次更新时间为 2022 年 06 月 05 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「redis」 「orm」 「memcache」 「cache」 「nova」 「laravel」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 mostafaznv/laracache 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 mostafaznv/laracache 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 mostafaznv/laracache 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Simple to use mutex implementation that can use flock, memcache, memcached, mysql or redis for locking
Microservice RPC through message queues.
Kinikit - PHP Application development framework MVC component
Graphic stand-alone administration for memcached to monitor and debug purpose
PHP Database ORM for Symfony1. Do NOT use for new projects: please move to a newest Symfony release and Doctrine2
The CodeIgniter Redis package
统计信息
- 总下载量: 50.31k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 272
- 点击次数: 35
- 依赖项目数: 1
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2022-06-05