slydeath/laravel5-nested-caching

Laravel 5.8 的嵌套缓存

3.2 2019-10-05 16:24 UTC

This package is auto-updated.

Last update: 2024-09-15 13:06:02 UTC


README

警告!!!

此包不再维护,请使用 https://github.com/SlyDeath/laravel-nested-caching 代替

Laravel 5 的嵌套缓存

Latest Stable Version Total Downloads License

版本

版本 3.* 用于 Laravel 5.8,对于 5.6-5.7 使用版本 2.*

安装

将包添加到 composer.json

composer require slydeath/laravel5-nested-caching

打开 config/app.php 并将服务提供者添加到 providers 数组中

SlyDeath\NestedCaching\NestedCachingServiceProvider::class,

为了放置配置文件,执行

php artisan vendor:publish --provider="SlyDeath\NestedCaching\NestedCachingServiceProvider" --tag=config

为了使用本库,需要支持标签的缓存驱动程序,这包括 MemcachedRedis

.env 文件中为 Memcached 指定

CACHE_DRIVER=memcached

对于 Redis

CACHE_DRIVER=redis

同时,为了使用 Redis,还需要安装包 predis/predis

composer require predis/predis

如何使用?

缓存任何 HTML 段落

为了缓存任何 HTML 段落,只需简单地将要缓存片段的键传递给 @cache 指令

@cache('simple-cache')
    <div>Это произвольный кусок HTML который будет закэширован по ключу "simple-cache"</div>
@endcache

缓存模型

在需要缓存的模型类中添加 NestedCacheable 特性

use SlyDeath\NestedCaching\NestedCacheable;

class User extends Model
{
    use NestedCacheable;
}

在模板中,为了缓存模型,需要将模型的实例传递给 @cache 指令

@cache($user)
    <div>Кэширование модели App\User:</div>
    <ul>
        <li>Имя: {{ $user->name }}</li>
        <li>Email: {{ $user->email }}</li>
    </ul>
@endcache

缓存模型指定时间

为了缓存模型指定时间,将生命周期(分钟数)作为第二个参数传递

@cache($user, 1440)
    <div>...</div>
@endcache

更新“父”

为了在更新模型时同时刷新“父”模型的缓存,需要更新父模型的 updated_at 字段

use SlyDeath\NestedCaching\NestedCacheable;

class CarUser extends Model
{
    use NestedCacheable;

    protected $touches = ['user']; // Указываем родителя

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

使用示例

resources/views/user.blade.php

@cache($user)
    <section>
        <h2>Автомобили пользователя {{ $user->name }}</h2>
        <ul>
            @foreach($user->cars as $car)
                @include('user-car');
            @endforeach
        </ul>
    </section>
@endcache

resources/views/user-car.blade.php

@cache($car)
    <li>{{ $car->brand }}</li>
@endcache

缓存集合

缓存集合的示例

@cache($users)

    @foreach ($users as $user)
        @include('user');
    @endforeach
    
@endcache