hkp22/cache-laraview-fragments

缓存Laravel视图片段。

1.0.0 2018-09-20 16:40 UTC

This package is auto-updated.

Last update: 2024-09-21 21:04:20 UTC


README

Laravel视图片段缓存支持。

安装

Composer

使用Composer将包下载到项目中。

composer require hkp22/cache-laraview-fragments

注册服务提供者

Laravel 5.5(或更高版本)使用包自动发现,因此不需要您手动添加ServiceProvider。

对于Laravel 5.4或更早版本,在app/config/app.php中包含服务提供者。

'providers' => [
    Hkp22\CacheLaraViewFragments\CacheLaraViewFragmentServiceProvider::class,
],

缓存驱动器

此包已使用Laravel标签(如Cache::tags('foo'))来存储缓存。因此,您必须使用支持标签的Laravel缓存驱动程序,如MemcachedRedis

请确保在.env文件中使用所需的CACHE_DRIVER

CACHE_DRIVER=redis

使用方法

安装包后,您可以在视图中使用@cache Blade指令。

@cache('my-cache-key')
    <div>
        <h1>Hello World</h1>
    </div>
@endcache

在生产环境中,这将永久缓存HTML片段。另一方面,在本地开发中,每次刷新页面时,它将自动为您清除相关的缓存。

清除缓存

由于您的生产服务器将永久缓存片段,您应该在部署过程中添加一个清除相关缓存的步骤。

Cache::tags('views')->flush();

缓存模型

考虑以下示例

@cache($post)
    <article>
        <h2>{{ $post->title }}></h2>
        <p>Written By: {{ $post->author->username }}</p>

        <div class="body">{{ $post->body }}</div>
    </article>
@endcache

在上面的示例中,$post对象被传递给@cache指令而不是字符串。它将在模型上查找getCacheKey()方法,该方法在Hkp22\CacheLaraViewFragments\Cacheable特性中定义。因此,在模型中使用此特性。

use Hkp22\CacheLaraViewFragments\Cacheable;

class Post extends Eloquent
{
    use Cacheable;
}

模型的缓存键将包括对象的idupdated_at时间戳:App\Post/1-1537459253

注意:由于updated_at时间戳被用于缓存键,因此每当帖子更新时,缓存键都会更改。

触碰

考虑以下示例:resources/views/posts/_post.blade.php

@cache($post)
    <article>
        <h2>{{ $post->title }}</h2>

        <ul>
            @foreach ($post->comments as $comment)
                @include ('posts/_comment')
            @endforeach
        </ul>
    </article>
@endcache

resources/views/posts/_comment.blade.php

@cache($post)
    <li>{{ $post->body }}</li>
@endcache

在上面的示例中,每当创建新的评论或更新现有评论时,它不会更改视图HTML,因为视图HTML是从缓存中获取的。

为了修复这个问题,需要在子模型(在这种情况下是评论模型)中添加$touches。因此,每当创建或更新评论时,它就会更新父模型的updated_at时间戳。

因此,在这种情况下,Comment模型应该像这样

<?php

namespace App;

use Hkp22\CacheLaraViewFragments\Cacheable;
use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    use Cacheable;

    protected $touches = ['post'];

    public function post()
    {
        return $this->belongsTo(Post::class);
    }
}

这里的$touches = ['post']指示Laravel在每次评论更新时更新post关系的时间戳。

缓存集合

您还可以缓存集合。

@cache($posts)
    @foreach ($posts as $post)
        @include ('post')
    @endforeach
@endcache