chrgriffin / laravel-cacheable

一个用于轻松缓存方法调用的 GOAOP 实现。

v1.0.2 2020-03-16 01:09 UTC

This package is auto-updated.

Last update: 2024-08-29 05:24:41 UTC


README

Build Status Coverage Status

Laravel Cacheable

laravel-cacheable 通过在方法上添加注释,使任何任意类方法的自动缓存变得简单,使用配置的 Laravel 缓存驱动程序。

use LaravelCacheable\Annotations\Cache;

class MyClass
{
    /** @Cache(seconds=3600) */
    public function cacheMe(): string 
    {
        return 'Hello!';
    }
}

安装

使用 composer 在您的 Laravel 项目中安装

composer install chrgriffin/laravel-cacheable

如果您的 Laravel 版本支持自动发现(5.5 及以上),则已完成!

对于较旧的 Laravel 版本,您需要编辑 config/app.php 文件,将服务提供者在 providers 数组中包含

return [
    // ...
    'providers' => [
        // ...
        LaravelCacheable\ServiceProvider::class
    ]
];

用法

配置(可选)

laravel-cacheable 使用 GOAOP 来构建类的缓存版本,然后对其应用方法拦截器。默认情况下,该包将使用 Laravel 框架缓存目录作为其缓存。默认情况下,它还会在您的整个 app 目录中搜索缓存注释。这两个配置都可以被覆盖。首先,复制包配置

php artisan vendor:publish --provider="LaravelCacheable\ServiceProvider"

现在,在 config/laravel-cacheable.php 中,您可以覆盖默认的包配置

return [
    'cache' => [
        // this is where laravel-cacheable will store cached versions of your classes
        storage_path('framework/cache/laravel-cacheable')
    ],
    // this is an array of all the paths laravel-cacheable will 'scan' for Cache annotations
    'paths' => [
        app_path()
    ]
];

缓存方法返回值

安装此包后,缓存方法调用结果就像确保您的 Laravel 缓存已设置好,然后在您的该方法上添加注释一样简单。

use LaravelCacheable\Annotations\Cache;

class MyClass
{
    /** @Cache */
    public function cacheMe(): string 
    {
        return 'Hello!';
    }
}

指定自定义缓存时间

默认情况下,laravel-cacheable 将缓存方法返回值 30 分钟。如果您想缓存方法不同的时长,可以在注释中添加一个 seconds 属性。

use LaravelCacheable\Annotations\Cache;

class MyClass
{
    /** @Cache(seconds=3600) */
    public function cacheMe(): string 
    {
        return 'Hello!';
    }
}

高级行为

仅使用文档注释就足以自动缓存方法的结果。对于更高级的行为,您还需要使用 Cacheable 特性。

use LaravelCacheable\Annotations\Cache;
use LaravelCacheable\Traits\Cacheable;

class MyClass
{
    use Cacheable;

    /** @Cache(seconds=3600) */
    public function cacheMe(): string 
    {
        return 'Hello!';
    }
}

绕过缓存

一旦您的类使用了 Cacheable 特性,您可以在方法调用之前通过链式调用 ->withoutCache() 来绕过特性。

// bypasses cache
(new MyClass())->withoutCache()->cacheMe();

请注意,这将绕过获取和设置缓存,该方法的返回值将不会被缓存。

注意

laravel-cacheable 会检查方法名称和传递的参数,以确定是否应从缓存中提取返回值。如果传递了不同的参数,将创建一个新的缓存索引。

(new MyClass())->cacheMe('argument 1');

// this method call will not use the cached return from the first one
(new MyClass())->cacheMe('argument 2');