Share a Laravel useful Cache macro _ PHP

Source: Internet
Author: User
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.

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.