簡體   English   中英

在Laravel中緩存查詢的更優雅或更有效的方法是什么

[英]What is more elegant or more efficient way to cache queries in Laravel

這就是目前緩存查詢的方式,我認為在更新后表中的數據發生更改時,很難使用模型事件來更新緩存,因為我需要更新多個緩存。

<?php namespace App\Repositories;

use App\Models\Book; //my model
use \Cache;

class BookEloquentRepository implements BookRepositoryInterface{

    protected $cache_enabled = true;
    protected $cache_key = "book";


    public function __construct(Book $book){
        $this->book = $book;
    }


    public function find($id)
    {
        $this->cache_key = $this->cache_key ."_find_{$id}";

        if( $this->cache_enabled && Cache::has($this->cache_key) ) return Cache::get($this->cache_key);

        $books = $this->book->find($id);

        Cache::forever($this->cache_key, $books);

        return $books;
    }


    public function all()
    {
        $this->cache_key = $this->cache_key ."_all";

        if( $this->cache_enabled && Cache::has($this->cache_key) ) return Cache::get($this->cache_key);

        $books = $this->book->all();

        Cache::forever($this->cache_key, $books);

        return $books;
    }


    public function allPublished()
    {
        $this->cache_key = $this->cache_key ."_allPublished";

        if( $this->cache_enabled && Cache::has($this->cache_key) ) return Cache::get($this->cache_key);

        $books = $this->book->where('published', 1);

        Cache::forever($this->cache_key, $books);

        return $books;
    }
}

這是正確的方法嗎? 我面臨的挑戰是記錄更改時如何更新緩存

我想知道是否有可能只為所有記錄保留一個緩存,並且能夠執行此類操作而不會影響數據庫。

 $books = Cache::get('books');

 $book = $books->find(1);

 $published = $books->where('published', 1)->get();

這樣,當使用模型事件在表更新后記錄更改時,我只能更新一次緩存“ books”

$published = Cache::remember('published', $minutes, function() {
    return Book::where('published', 1)->get();
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM