[英]What is more elegant or more efficient way to cache queries in Laravel
This is how am presently caching queries and i think it difficult to use model events to update cache when data change in tables after update because i need to update multiple caches. 这就是目前缓存查询的方式,我认为在更新后表中的数据发生更改时,很难使用模型事件来更新缓存,因为我需要更新多个缓存。
<?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;
}
}
Is this the right way to do this? 这是正确的方法吗? The challenge i have with these is how to update caches when record changes 我面临的挑战是记录更改时如何更新缓存
I want to know if its possible to maintain only one cache for all records and be able to do stuffs like this without hitting the database. 我想知道是否有可能只为所有记录保留一个缓存,并且能够执行此类操作而不会影响数据库。
$books = Cache::get('books');
$book = $books->find(1);
$published = $books->where('published', 1)->get();
This way i can only update only once cache 'books' when record changes after table update using model events 这样,当使用模型事件在表更新后记录更改时,我只能更新一次缓存“ books”
$published = Cache::remember('published', $minutes, function() {
return Book::where('published', 1)->get();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.