A simple example of advanced optimization of Laravel cache

Source: Internet
Author: User
Tags closure redis

Laravel provides five cache driver modes:

• File system
• Database
• Memcached
• APC
• Redis
• Memory (Arrays)

By default, Laravel is configured to use the file system cache driver, which does not need to be configured. the file system driver stores cached items as files in the storage/cache directory. if you are satisfied with this driver, no other configuration is required. use it directly:

Tip: before using the file system cache driver, make sure that your storage/cache directory is writable.


When using Cache in Laravel, you can use the Cache Facade, which is convenient and elegant. The common Cache method is as follows:


$ Value = cache-> get ('key ');
If ($ value = false ){
$ Value = DB-> where ('XX')-> get ();
$ Value = cache-> set ('key', $ value );
Cache-> expire ('key', 1800 );
}

This logic uses the remember method and closure function in Laravel, which can be very elegant and convenient to express. The three lines of code implement the above process.


As follows:


Use App \ Http \ Requests;
Use App \ Models \ Wp;
Use Illuminate \ Support \ Facades \ Cache;
 
Class BlogController extends Controller
{
Private $ indexPostsKey = 'com. tanteng. me. index. blog. Posts ';
 
Public function index ()
    {
$ NewPosts = Cache: store ('redis ')-> remember ($ this-> indexPostsKey, 30, function (){
Return Wp: type ('post')-> status ('Publish ')-> orderBy ('post _ date', 'desc')-> take (16) -> get ();
});
Return View ('index/blog ', compact ('newposts '));
    }
}

This is just a simple example of using cache in Laravel. This is also the way to obtain the list of Blog pages on this site. First, find the cache, do not query the database returned in the closure, and cache it for 30 minutes, cache: store ('file') allows you to conveniently use different Cache methods.

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.