Laravel provides a good caching tool, the manual introduces some basic usage, such as get,put,forget,forever, in the beginning I was like the following use:
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, automatically determining whether the cache exists, and does not exist, fetching from the database and writing to the cache.
It was later found that the model also came with remember and rememberforever methods, such as:
The
code is as follows:
$article = article::rememberforever (' article_1 ')->where (' id ', ' = ', 1);
This is limited in that it is not possible to cache data completely when complex queries, such as with () preloading associated data.
It was then found that the cache could also customize the macro method like response, and then try the following:
The
code is as follows:
//Register cache Access Macros
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::p ut ($key, $data, $minutes);
}
}
return $data;
});
This method can be placed in the bootstrap/start.php, can also be placed in the filter App::before (), with their own project convenient bar, see How to use:
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 ']);
});
Personally, I like this kind of wording. I hope you can enjoy the content of this article.