About Laravel's caching method

不言
Release: 2023-04-01 06:46:02
Original
1724 people have browsed it

This article mainly introduces relevant information about sharing a useful caching method in Laravel. Friends who need it can refer to it

The caching tool provided by Laravel is very easy to use. The manual introduces some basic Usage, such as get, put, forget, forever, etc. At first, I used it as follows:

if (!$article = Cache::get('article_1')) {
    $article = Article::find(1);
    Cache::forever('article_1',$article);
}
Copy after login

This is the most basic usage. It automatically determines whether the cache exists. If it does not exist, it will be fetched from the database. Write cache.

Later I discovered that the model also comes with the remember and rememberForever methods. For example, it can be like this:

$article = Article::rememberForever('article_1')->where('id','=',1);
Copy after login

This has limitations and cannot completely cache the data during complex queries. For example, using with() to pre-set The related data cannot be cached while the related data is being loaded.

Then I discovered that Cache can also customize macro methods like Response, so I tried the following:

//注册缓存存取宏
Cache::macro('want',function($key,$minutes=0,$callback){
    if (!$data = Cache::get($key)) {
        $data = call_user_func($callback);
        if ($minutes == 0) {
            Cache::forever($key,$data);
        } else {
            Cache::put($key,$data,$minutes);
        }
    }
    return $data;
});
Copy after login

This method can be placed in bootstrap/start.php or in filter. In App::before(), it’s convenient for your own project. Let’s see how to use it:

$id = Input::get('id');
$article = Cache::want('article_'.$id,0,function() use ($id){
    return Article::with('tags')->findOrFail($id,['id','cid','title','content_html as content','created_at','updated_at']);
});
Copy after login

I personally like this way of writing. I hope you all like the content of this article.

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

Laravel Redis Problem analysis of multiple processes taking queues at the same time

About data migration and development in Laravel Analysis of data filling

#

The above is the detailed content of About Laravel's caching method. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template