joshembling/cache-machine

CacheMachine 允许您在 Laravel 项目中轻松地进行“提取”和“存入”缓存。

v1.1.1 2024-03-17 13:42 UTC

README

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

关于

CacheMachine 是一种简单、轻量级的缓存管理方法,适用于您的 Laravel 模型。您可以使用特定的键来“提取”缓存数据,并在需要时同时“存入”(保存)新的缓存条目。

CacheMachine 的一个关键优势是在模型保存或删除操作期间自动触发。这确保您的缓存始终是最新的,而无需手动干预。对于那些更喜欢更多控制的人,您可以灵活地根据需要强制更新缓存。一旦创建,缓存将无限期地持续,直到您的模型进行更新。

CacheMachine 特别适合各种用例,包括文章和博客文章、产品定价信息、选择字段、翻译、用户资料、图片等。

虽然 CacheMachine 是围绕缓存模型查询设计的,但它具有多功能性。您可以将任何数据纳入缓存键中,确保它们与模型更新保持一致。

注意:请注意,如果您的模型更新频繁,例如每几秒钟更新一次,建议您根据特定的性能需求配置自己的缓存方法。

兼容性

您可以使用任何您想要的缓存提供商,例如 Redis、DynamoDB。有关进一步的帮助,请参阅 Laravel 缓存文档

此包与 Laravel 版本 10 和 11 以及 PHP 版本 >= 8.2 兼容。

安装

您可以通过 composer 安装此包

composer require joshembling/cache-machine

用法

要使用 CacheMachine,每个模型的用法结构都将相同。

  1. 添加 CacheMachine 特性。
use JoshEmbling\CacheMachine\CacheMachine;

class Post extends Model
{
    use CacheMachine;

    // ...
}
  1. 向您的模型添加 cacheKeys() 方法。此方法必须返回一个结构为 string => callable 的数组。
use JoshEmbling\CacheMachine\CacheMachine;

class Post extends Model
{
    use CacheMachine;

    /**
     * @var array<string, callable>
     */
    public static function cacheKeys(): array
    {
        $keys = [
            // Cache all posts with the eloquent query as the callback
            'all_posts' => fn () => self::all(),
        ];

        return $keys;
    }

    // ...
}
  1. 您可能更喜欢在这个类中动态引用键作为常量或属性。
use JoshEmbling\CacheMachine\CacheMachine;

class Post extends Model
{
    use CacheMachine;

    const ALL = 'all_posts';
    const SELECT = 'select_posts';

    /**
     * @var array<string, callable>
     */
    public static function cacheKeys(): array
    {
        $keys = [
             // Cache all posts
            self::ALL => fn () => self::all(),

             // Cache all posts in a key => value format
            self::SELECT => fn () => self::get()->mapWithKeys(
                fn ($type) => [
                    $type->id => $type->title,
                ]
            ),
        ];

        return $keys;
    }

    // ...
}

设置好模型后,您就可以 withdraw() 缓存。如果不存在,CacheMachine 将在回调函数有效时自动 deposit 缓存。

换句话说,CacheMachine 会从缓存中获取,如果存在,或者查询数据库如果不存在。

// You may pass a string to the withdraw method.
Post::withdraw('all_posts');

// Or one of your model's static properties, relating to a key defined in the `cacheKeys()` method.
Post::withdraw(Post::ALL);

如果您想手动保存到缓存,例如,您手动向数据库中添加了记录而没有触发模型观察者,您可以执行以下操作

Post::forceFetch(Post::ALL)

集合

如果您的 cacheKeys() 中的回调函数返回 Eloquent 查询,您可以使用任何 集合方法 来过滤您的结果。一旦父查询被缓存,您就不需要再次查询数据库。

以下是一个简单的博客网站示例

// Fetch all posts to display on an archive
Post::withdraw('all_posts');

// Display a single blog article
Post::withdraw('all_posts')
    ->firstWhere('id', 2);

// Filter a user search query
Post::withdraw('all_posts')
    ->where('title', 'like', '%Laravel%')
    ->orWhere('published_at', '>', now()->subDays(30))
    ->map(fn ($post) => strtoupper($post->title))
    ->sortDesc();

您可能希望进一步增强您的集合,以减少对数据库的过度使用。如果您需要像分页、分块等额外的功能,而这些功能不是 Laravel 默认提供的,我建议您使用 Spatie 的 laravel-collection-macros

测试

composer test

变更日志

请参阅变更日志获取关于最近更改的更多信息。

贡献指南

请参阅贡献指南以获取详细信息。

安全漏洞

请查看我们的安全策略了解如何报告安全漏洞。

致谢

许可证

MIT许可证(MIT)。请参阅许可证文件获取更多信息。