Share a laravel handy cache macro

Source: Internet
Author: User

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.

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.