Home >Backend Development >PHP Tutorial >Share a useful Cache macro for Laravel, laravelcache macro_PHP tutorial
The caching tool provided by Laravel is very useful. The manual introduces some basic usage, such as get, put, forget , forever, etc. At first I used it like this:
Copy code The code is as follows:
if (!$article = Cache::get('article_1')) {
$article = Article::find(1);
Cache::forever('article_1',$article);
}
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 and written to the cache.
Later I discovered that the model also comes with the remember and rememberForever methods. For example, it can be like this:
Copy code The code is as follows:
$article = Article::rememberForever('article_1')->where('id','=',1);
This has limitations. It cannot completely cache data during complex queries. For example, when using with() to preload related data, related data cannot be cached.
Then I discovered that Cache can also customize macro methods like Response, so I tried the following:
Copy code The code is as follows:
//Register cache access macro
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;
});
This method can be placed in bootstrap/start.php, or it can be placed in App::before() in filter. It is convenient for your own project. Let’s see how to use it:
Copy code The code is as follows:
$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']);
});
I personally like this way of writing. I hope you all like the content of this article.