bit-mx / cache-entities
创建可缓存的实体
1.0.3
2024-05-28 17:55 UTC
Requires
- php: ^8.2
- illuminate/support: ^10.0 || ^11.0
Requires (Dev)
- fakerphp/faker: ^1.23
- larastan/larastan: ^2.9
- laravel/pint: ^1.15
- orchestra/testbench: ^9.0
- pestphp/pest: ^2.34
- pestphp/pest-plugin-laravel: ^2.4
- phpstan/extension-installer: ^1.3
- tomasvotruba/type-coverage: ^0.2.8
This package is auto-updated.
Last update: 2024-09-28 18:42:38 UTC
README
使用 Cache Entities 轻松管理你的缓存。
目录
简介
Cache Entities 是一个允许您使用简单且干净的 API 来管理缓存的包。
安装
您可以通过 composer 安装此包
composer require bit-mx/cache-entities
兼容性
此包与 Laravel 10.x 及以上版本兼容。
由于 Laravel 11 需要 php 8.2,因此此包与 php 8.2 及以上版本兼容。
入门
创建 Cache Entity 类
要创建 Cache Entity,您需要扩展 CacheEntity 类并实现 resolveKey、resolveTtl 和 resolveValue 方法。
namespace App\CacheEntities; use BitMx\CacheEntities\CacheEntity; use App\Models\User; use Carbon\CarbonInterval; class CurrentUserCache extends CacheEntity { public function __construct( protected int $id, ) { } protected function resolveKey(): string { return sprintf('current_user:%s', $this->id); } protected function resolveTtl(): CarbonInterval { return CarbonInterval::days(12); } protected function resolveValue(): mixed { return User::find($this->id); } }
您可以使用 artisan 命令来创建新的 Cache Entity
php artisan make:cache-entity CurrentUserCacheEntity
此命令将在 app/cacheEntities
目录中创建新的 Cache Entity。
驱动
您可以通过重写 resolveCacheStore 方法来设置驱动程序名称。
namespace App\CacheEntities; use BitMx\CacheEntities\CacheEntity; use App\Models\User; use Carbon\CarbonInterval; class CurrentUserCache extends CacheEntity { protected function resolveCacheStore(): string { return 'redis'; } }
获取缓存值
要获取缓存值,您可以使用 get 方法。
use App\CacheEntities\CurrentUserCacheEntity; $cacheEntity = new CurrentUserCacheEntity(1); $user = $cacheEntity->get();
辅助方法
您可以使用以下辅助方法来处理缓存
exists
exists 方法如果缓存键存在则返回 true,否则返回 false。
use App\CacheEntities\CurrentUserCacheEntity; $cacheEntity = new CurrentUserCacheEntity(1); $user = $cacheEntity->get(); if ($cacheEntity->exists()) { // The cache key exists } else { // The cache key does not exist }
doesNotExist
doesNotExist 方法如果缓存键不存在则返回 true,否则返回 false。
use App\CacheEntities\CurrentUserCacheEntity; $cacheEntity = new CurrentUserCacheEntity(1); $user = $cacheEntity->get(); if ($cacheEntity->doesNotExist()) { // The cache key does not exist } else { // The cache key exists }
forget
forget 方法移除缓存键。
use App\CacheEntities\CurrentUserCacheEntity; $cacheEntity = new CurrentUserCacheEntity(1); $user = $cacheEntity->get(); $cacheEntity->forget();