slydeath/laravel-nested-caching

带有缓存栈的Laravel嵌套缓存

3.0 2023-06-20 08:21 UTC

This package is auto-updated.

Last update: 2024-09-20 11:14:49 UTC


README

Latest Stable Version Total Downloads License

最低要求

  • PHP 7.4
  • Laravel 8

安装

将包添加到 composer.json

composer require slydeath/laravel-nested-caching

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

SlyDeath\NestedCaching\NestedCachingServiceProvider::class,

放置配置文件,运行

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

如何使用?

缓存任何HTML块

要缓存任何HTML块,只需将缓存键传递给 @cache 指令片段

@cache('simple-cache')
<div>
    This is an arbitrary piece of HTML that will be cached
    using the «simple-cache» key
</div>
@endCache

模型缓存

要启用模型缓存支持,添加 NestedCacheable 特性

use SlyDeath\NestedCaching\NestedCacheable;

class User extends Model
{
    use NestedCacheable;
}

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

@cache($user)
<div>App\User model caching:</div>
<ul>
    <li>Name: {{ $user->name }}</li>
    <li>Email: {{ $user->email }}</li>
</ul>
@endCache

指定时间缓存模型

要缓存模型一定时间,指定分钟数作为第二个参数

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

更新“父”缓存

要更新“父模型”的缓存,我们需要设置 touches

use SlyDeath\NestedCaching\NestedCacheable;

class CarUser extends Model
{
    use NestedCacheable;

    // Specifying the parent relations
    protected $touches = ['user']; 

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

使用示例

resources/views/user.blade.php

@cache($user)
<section>
    <h2>User's cars {{ $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

如何删除堆栈缓存?

只需在页面底部运行此代码

app(SlyDeath\NestedCaching\CacheStack::class)->clearCache();

与其他缓存的流程

如何收集键?

如果启用 another-caching,则 SlyDeath\NestedCaching\CacheWrittenListener 会自动收集键,但如果你想在其他地方使用它们,则必须手动保存(在执行应用程序结束时)

app(\SlyDeath\NestedCaching\CacheStack::class)->getAnotherCaches();

如何清除其他缓存的堆栈?

只需调用 clearAnotherCaches 方法

 app(\SlyDeath\NestedCaching\CacheStack::class)->clearAnotherCaches();

如何为不同页面保存键?

你可以动态生成缓存键(例如从页面ID生成)

app(\SlyDeath\NestedCaching\CacheStack::class)->setAnotherKey('my-cache-key-prefix:' . optional($page)->id)->getAnotherCaches();

如何使用自定义缓存键清除其他缓存的堆栈?

只需调用 clearAnotherCaches 方法并提供键

 app(\SlyDeath\NestedCaching\CacheStack::class)->setAnotherKey('my-cache-key-prefix:' . optional($page)->id)->clearAnotherCaches();

启用 PhpStorm 支持

转到 设置 → PHP → Blade,然后取消选中 使用默认设置。转到 指令 选项卡,然后按“+”添加另一个自定义指令

  • 名称:cache
  • 复选框 有参数true
  • 前缀:<?php if ( ! app('SlyDeath\NestedCaching\BladeDirectives')->cache(
  • 后缀:)) { ?>

添加不带参数的结束指令

  • 名称:endcacheendCache,无论你使用哪个