This article mainly introduces how to share the useful Cache macro method of Laravel. For more information, see the Cache tool provided by Laravel, the manual describes some basic usage, such as get, put, forget, and forever. at the beginning, I used them as follows:
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 retrieve and write the cache from the database.
Later, we found that the model also comes with the remember and rememberForever methods. for example:
The code is as follows:
$ Article = Article: rememberForever ('article _ 1')-> where ('id', '=', 1 );
This has limitations. in complex queries, data cannot be completely cached. for example, when you use with () to pre-load associated data, the associated data cannot be cached.
Then it is found that the Cache can also customize the macro method like Response, and then try the following:
The code is as follows:
// Register the 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 stored in bootstrap/start. php, or in App: before () in the filter. it is convenient for your project and you can see how to use it:
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 method. I hope you will like this article.