Composer在线学习地址:学习地址
作为php开发者,我们深知缓存的重要性。它能让你的应用像跑车一样飞驰,用户体验蹭蹭上涨。但就像任何强大的工具一样,如果使用不当,缓存也会变成一个“甜蜜的负担”。
想象一下这样的场景:你的Laravel应用中,首页需要展示“热门书籍”,用户个人中心需要“推荐课程”,API接口需要“最新文档列表”。为了提高响应速度,你自然会想到使用缓存。于是,你可能在控制器、服务层甚至模型中,到处散布着
Cache::remember()
Cache::put()
起初,这看起来很有效。但很快,问题接踵而至:
这些痛点,相信很多开发者都深有体会。它们不仅拖慢了开发效率,也为项目的长期维护埋下了隐患。那么,有没有一种更优雅、更统一的方式来管理这些缓存呢?
studocu/cacheable-entities
正是为了解决上述问题,StuDocu团队开发并开源了
studocu/cacheable-entities
其核心思想是:将一个需要缓存的数据查询或计算逻辑封装成一个独立的“实体”,这个实体自身知道如何生成缓存键、设置过期时间,以及如何获取数据。
使用Composer安装非常简单:
<pre class="brush:php;toolbar:false;">composer require studocu/cacheable-entities
Cacheable
要让一个类成为可缓存实体,它需要实现
StuDocu\CacheableEntities\Contracts\Cacheable
getCacheTTL(): int
getCacheKey(): string
get(): mixed
让我们看一个获取“推荐书籍”的例子:
<pre class="brush:php;toolbar:false;"><?php
use Illuminate\Database\Eloquent\Collection;
use StuDocu\CacheableEntities\Contracts\Cacheable;
class RecommendedBooksQuery implements Cacheable
{
public function getCacheTTL(): int
{
// 缓存24小时
return 3600 * 24;
}
public function getCacheKey(): string
{
// 统一的缓存键命名,方便管理
return "books:popular.v1";
}
public function get(): Collection
{
// 实际的业务逻辑,从数据库查询热门书籍
return Book::query()
->wherePopular()
->orderByDesc('document_popularity_scores.score')
->take(config('popular.books.limit'))
->get();
}
}现在,我们的“推荐书籍”查询逻辑及其缓存策略被清晰地封装在一个类中,一目了然。
SerializableCacheable
直接缓存Eloquent Collection可能会导致缓存体积过大,或者在反序列化时丢失关联关系。
studocu/cacheable-entities
SerializableCacheable
实现
SerializableCacheable
serialize(mixed $value): mixed
unserialize(mixed $value): mixed
<pre class="brush:php;toolbar:false;"><?php
// ... (省略部分use和类定义)
use StuDocu\CacheableEntities\Contracts\SerializableCacheable;
class RecommendedBooksQuery implements Cacheable, SerializableCacheable
{
// ... (getCacheTTL, getCacheKey, get 方法不变)
/**
* @param Collection<Book> $value
* @return array<int>
*/
public function serialize(mixed $value): array
{
// 只缓存书籍的ID数组
return $value->pluck('id')->all();
}
/**
* @param int[] $value
* @return Collection<int, Book>
*/
public function unserialize(mixed $value): Collection
{
// 从缓存的ID数组中,重新加载书籍对象
// 注意:这里需要处理可能存在的顺序问题,例如使用 array_flip + sortBy
if (!is_array($value) || empty($value)) {
return Collection::empty();
}
$booksFastAccess = array_flip($value); // 用于快速查找原始顺序
return Book::query()
->findMany($value)
->sortBy(fn (Book $book) => $booksFastAccess[$book->id] ?? 999) // 恢复原始顺序
->values();
}
}通过这种方式,我们不仅减小了缓存的体积,还确保了在反序列化时能够获取到最新、完整的书籍对象,避免了潜在的数据不一致问题。如果反序列化过程中发现缓存值损坏(例如格式错误),你可以抛出
\StuDocu\CacheableEntities\Exceptions\CorruptSerializedCacheValueException
SyncCache
AsyncCache
studocu/cacheable-entities
SyncCache
get()
AsyncCache
null
使用起来非常直观:
<pre class="brush:php;toolbar:false;"><?php use StuDocu\CacheableEntities\AsyncCache; use StuDocu\CacheableEntities\SyncCache; $query = new RecommendedBooksQuery(); // 在API接口中,需要立即获取结果,即使未命中也要同步计算 $booksForApi = resolve(SyncCache::class)->get($query); // 在Web页面中,可以先显示空数据,后台异步填充缓存,避免阻塞用户 $booksForWeb = resolve(AsyncCache::class)->get($query); // 可能返回空集合
此外,如果你需要获取数据的实时值,不经过任何缓存,可以直接调用实体自身的
get()
<pre class="brush:php;toolbar:false;">$realtimeBooks = $query->get(); // 永远获取最新数据
SelfCacheable
为了进一步简化调用,
studocu/cacheable-entities
SelfCacheable
SyncCache
AsyncCache
<pre class="brush:php;toolbar:false;"><?php
// ... (省略部分use和类定义)
use StuDocu\CacheableEntities\Concerns\SelfCacheable;
class RecommendedBooksQuery implements Cacheable, SerializableCacheable
{
use SelfCacheable; // 使用SelfCacheable Trait
// ... (其他方法不变)
}
$query = new RecommendedBooksQuery();
// 异步获取缓存值
$booksAsync = $query->getCachedAsync();
// 同步获取缓存值
$booksSync = $query->getCached();
// 清除该实体的缓存
$query->forgetCache();这种方式让代码更加简洁,逻辑更贴近业务实体本身。
resolve(SyncCache::class)->forget($query);
SelfCacheable
forgetCache()
SupportsDefaultValue
AsyncCache
null
studocu/cacheable-entities
如果你正在为应用中的缓存管理而头疼,或者希望构建一个更健壮、更易于维护的大型PHP应用,那么
studocu/cacheable-entities
以上就是告别缓存地狱:如何用studocu/cacheable-entities优雅管理复杂数据缓存的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号