Laravel _php Example of how to use caching cache data to relieve database query pressure

Source: Internet
Author: User
Tags smarty template
The example in this paper describes how Laravel uses caching cache data to alleviate the pressure of database queries. Share to everyone for your reference, as follows:

Yesterday want to make their own home page cache, to achieve similar to the effect of generating static page cache, in the group asked everyone how to do the cache, are very busy not many replies, I went to see the document, found the caching this part, in fact, before also have an impression, but no specific contact, as the name implies, is cached , that certainly and my needs a bit of contact, I looked carefully, found that is really too strong, after a very simple few steps, I modified the home page, with Firebug test, improved dozens of MS parsing time, of course, someone will laugh it is necessary, is not idle egg pain? Actually I think it's necessary, Just in my here to visit less people (actually no one still, hey ...), and I do in the homepage of the query is still very few, just once, is to get all the blog post, if a page has a seven or eight times or even 10 times query, I think this effect should be very obvious! (Of course, Raymond also mentioned the use of more advanced dedicated cache to do (memcached and the like), this is to get the server control, can freely install the software or the server has these caching mechanisms can be achieved, I need more simple, there is no such environment to do, So it's not considered here.)

Talk less, let's go, let's talk about my specific needs:

First, the implementation of the first page of the data cache, if there is no expiration of the cache, do not check the database, so that the basic simulation of the effect of the static page (of course, in fact, it is to be processed by PHP)

Two. Implement the function of refreshing the specified cache (only home page, on the single finger Refresh home cache, this feature, I did the admin module under

Specific implementation:

I. Consult the documentation to find a module that will help me achieve my needs

I checked the document, found that there is a caching such a module, as the name implies, is the cache, then it can help me, see first:

1. Http://laravel.com/docs/cache/config here is the implementation of the Laravel caching module

2. The document has the following description:

The Basics Imagine your application displays the ten most popular songs as voted on by your users. Do you really need to look up these ten songs every time someone visits your site? What if the could store them for ten minutes, or even an hour, allowing do dramatically speed up your application? Laravel ' s caching makes it simple.

I understand it simply as:

Assuming your app shows the top 10 popular songs the user voted on, do you really need to check out these 10 songs every time everyone visits your website? If you want to cache the query results for 10 minutes or an hour to speed up your application, Laravel The caching cache module can make the job incredibly simple.

Well, from that point forward, I've learned that this is exactly what I need now, and then I just have to find the corresponding usage and API, one step at a time.

Two. Learn the appropriate API, etc.

1. The above document, which is then looked down, has the following description:

By default, Laravel are configured to use the file system cache driver. It's ready-to-go out of the box with no configuration. The file system driver stores cached items as files in the cache directory. If you ' re satisfied with this driver, no other configuration is required. You're ready to start using it.

I understand it simply as:

By default, Laravel uses the file system as the driver of the cache, which is not required to be configured to use, the file system driver will cache the data in the cache directory in the file, if you think it is appropriate to do not need to do any other configuration directly to start using the line.

Of course, this is also in line with my idea, in fact, I just want to cache the page as a static page file, the user once again access to the output cache of static page is OK, if more advanced needs, you can use other drivers, database driver, memcached, Redis driver, very good very powerful!

2. Next, look at the use cases to find out how

Use case documentation in this: Http://laravel.com/docs/cache/usage

It can be seen that there are get, put, forever, remember, has, forget and other methods, the use of these methods is basically able to "words too literally" can be done, hehe

Specific use of the method of the document has been said to be detailed enough, the use of the method at a glance I will not elaborate, only in the code to say it

Three. Concrete implementation

1. The code before my home page

Class Home_controller extends Base_controller {public Function Get_index () {  $posts = post::with (' user ')     Join (' users ', ' users.id ', ' = ', ' Posts.post_author '),      order_by (' posts.created_at ', ' desc ')       ->get ( Array (' posts.id ', ' posts.support ', ' posts.against ', ' users.username ', ' posts.post_author ', ' posts.post_title ', ' Posts.post_body '));  $data = Array ();  foreach ($posts as $p) {   $data [] = Array (    ' id ' =  $p-ID,    ' support ' = $p-Support,    ' a Gainst ' = $p, against,    ' username ', $p-username,    ' post_author ' + $p Post_author,
   ' post_title ' = $p, Post_title,    ' post_body ', $p-post_body   );  }  Return View::make (' Home.index ')    with (' posts ', $data);}}

This is my home controller, the role of only one, is to get all the posts from the blog, and then output, every time someone visits, to check the table, if not published new blog, also to check the table, indeed there are a lot of unnecessary expenses

2. Here is the code after I modified:

Class Home_controller extends Base_controller {public Function Get_index () {//Add static cache support//If there is no static page cache, immediately cache if (!   Cache::has (' Staticpagecache_home ')) {$data = array (); $posts = Post::with (' user ')->join (' Users ', ' users.id ', ' = ', ' Posts.post_author '), order_by (' Posts.crea Ted_at ', ' desc ')->get (Array (' posts.id ', ' posts.support ', ' posts.against ', ' users.username ', ' Posts.post_author ')   , ' Posts.post_title ', ' posts.post_body '); foreach ($posts as $p) {$data [] = array (' id ' = $p-ID, ' support ' = $p-support, ' against ' = $p, against, ' username ', $p, username, ' post_author ' + $p post_author, ' post_t   Itle ' = $p, Post_title, ' post_body ', $p-post_body);   } $res = View::make (' Home.index ') with (' posts ', $data);  Cache::forever (' Staticpagecache_home ', $res); }//Returns the cached data return Cache::get (' Staticpagecache_home '); }}

I've used three APIs here.

1). Cache::has, the judgment is that if there is no current cache of the name Staticpagecache_home, go to fetch the data immediately

2). Cache::forever, this from the use case document is known as the "permanent cache" meaning, because I am generally very diligent, if published blog, and then go back to the background to refresh the cache immediately, so do not need to set the expiration Ah expiration time and so on, Of course, this is to be based on their specific needs.

3). Cache::get, this is the cache that takes the name of Staticpagecache_home from the cache and then returns as a response content

Well, just so simple, hehe, a basic cache function is finished, Laravel is really good!

3. Add Refresh cache function for background

Just stick with the code, but it's also simple:

//Refresh Home Cache (temporarily only support first page) public function Get_refreshcache () {/* @var $GID Admin Group ID */$GI D = 1;  if (Auth::user (), gid = = = 1) {$data = array (); $posts = Post::with (' user ')->join (' Users ', ' users.id ', ' = ', ' Posts.post_author '), order_by (' posts.created_a T ', ' desc ')->get (Array (' posts.id ', ' posts.support ', ' posts.against ', ' users.username ', ' posts.post_author ', '  Posts.post_title ', ' posts.post_body ')); foreach ($posts as $p) {$data [] = array (' id ' = $p-ID, ' support ' = $p-support, ' against ' =& Gt  $p, against, ' username ' = $p, username, ' post_author ' + $p post_author, ' post_title ' =  $p, Post_title, ' post_body ', $p-post_body);  } $res = View::make (' Home.index ') with (' posts ', $data);  Cache::forever (' Staticpagecache_home ', $res); Return ' Refresh Home cache successfully! '; } return ' Sorry, only the Administrators group is able to do this! ';} 

I add a project to the background, corresponding to this method, the method content and the home page of the same, take the data, and then Cache::forever refresh the cache, it is so simple, of course, the above auth::user () judgment is a simple judgment, only the Administrators group to perform the refresh operation, Oh

Well, all the content is so much, very simple, welcome children's shoes to shoot bricks!

More interested in laravel related content readers can view this site topic: "Laravel Framework Introductory and Advanced tutorial", "PHP Excellent Development Framework Summary", "Smarty Template Primer Basic Tutorial", "PHP date and Time usage summary", "PHP object-oriented Programming introduction tutorial "," PHP String Usage Summary "," Introduction to Php+mysql Database Operations "and" PHP common database Operation Skills Summary "

It is hoped that this article is helpful to the PHP program design based on Laravel framework.

  • Related 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.