Laravel method to mitigate the pressure of database query using caching cached data _php instance

Source: Internet
Author: User
Tags auth documentation memcached smarty template

The example in this article describes how Laravel uses caching cache data to mitigate the pressure of database queries. Share to everyone for your reference, specific as follows:

Yesterday I wanted to make a cache of the homepage of my blog, which is similar to the effect of generating static page caching. In the group asked everyone how to do the cache, are very busy not much reply, I went to see the document, found the caching this part, in fact, before also have the impression, but did not specifically contact, as the name implies, is the cache , that must be a bit of a connection to my needs, I looked seriously, found it is too strong, after a very simple few steps, I modified the home page, with Firebug test, improve the dozens of millisecond parsing time, of course, some people will laugh this is necessary, it is not idle eggs pain? Actually, I think it's necessary. It's just that I have a few visitors here (in fact, no one else at all. Hey ...), second, I do in the home page of the query is quite small, just once, is to get all the Bowen, if a page has a seven or eight or even 10 times query, I think this effect should be very obvious! (Of course, Raymond also mentions using more advanced proprietary caching (memcached), this is to be able to get the server control, the free installation of software or the server would have these caching mechanism can be achieved, I need to be relatively simple, there is no such environment to do, So we don't think about it here.

Talk less, start, talk about my specific needs:

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

Two. Realize refresh the specified caching function (here only the home page, on the single point to refresh the home page cache, this function, I did the admin module under

Specific implementation:

A. Consult the documentation to find the module that will help me achieve my requirements

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 documentation is described as follows:

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

My simple understanding is:

Assuming your app shows the top 10 popular songs that users vote for, do you really need to check out these 10 songs every time you visit your site? If you want to use 10 minutes or an hour to cache the results of your query to speed up your application, Laravel The caching cache module can make the work exceptionally simple.

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

Two. Learn the appropriate API and so on

1. Or 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 are satisfied with this driver, no other configuration are required. ' re ready to start using it.

My simple understanding is:

By default, Laravel uses the file system as a cache driver, which is available without configuration, and file system drivers store cached data in a file in a cached directory, and if you feel appropriate, do not need to do any other configuration directly to start using.

Of course, it's also in my mind, in fact, I just want to cache the page as a static page file, the user again access to the direct output cache static page OK, if you need more advanced requirements, you can also use other drivers, database-driven, memcached, Redis Drive, very good very powerful!

2. Next look at the use case to find out how

Use case documentation is here: Http://laravel.com/docs/cache/usage

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

The concrete use method document inside already said enough detail, the use method at a glance I don't elaborate, only in the code inside say

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,
    ' Against ' => $p-> against,
    ' username ' => $p-> username,
    ' post_author ' => $p-> post_author,< c15/> ' Post_title ' => $p-> post_title,
    ' post_body ' => $p-> post_body
   );
  Return View::make (' Home.index ')
    -> with (' posts ', $data);
 }


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

2. The following is my modified code:

Class Home_controller extends Base_controller {public Function Get_index () {//Add static cache support//cache if no static page cache exists ( !
   Cache::has (' Staticpagecache_home ')) {$data = array (); $posts = Post::with (' user ')->join (' Users ', ' users.id ', ' = ', ' posts.post_author ')-> order_by (' posts.cr Eated_at ', ' desc ')->get (Array (' posts.id ', ' posts.support ', ' posts.against ', ' users.username ', ' Posts.post_auth ')
   Or ', ' posts.post_title ', ' posts.post_body '); foreach ($posts as $p) {$data [] = array (' ID ' => $p-> ID, ' support ' => $p-> support, ' Aga
     Inst ' => $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);
 //Returns the cached data return Cache::get (' Staticpagecache_home ');

}
} 

I've used three APIs here.

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

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

3). Cache::get, this is to remove the cache of Staticpagecache_home from the cache, and then return as the response content

Well, it's so simple, oh, a basic caching function is done, laravel is really good!

3. Add refresh caching for the background

Stick to the code, but it's also simple:

//Refresh first page cache (only supports home page temporarily) 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 _at ', ' desc ')->get (Array (' posts.id ', ' posts.support ', ' posts.against ', ' users.username ', ' posts.post_author ', ' PO
  Sts.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);
 Return ' Refresh Home cache success! '
Return ' Sorry, only the Administrators group can do this! '; }

I added a project to the background, corresponding to this method, method content and the same as the home page, 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 administrator group can perform the refresh operation, Oh

Well, all the content is so much, very simple, welcome children's shoes to make a brick!

More interested in laravel related content readers can view the site topics: "Laravel Framework Introduction and Advanced Course", "PHP Excellent Development Framework Summary", "Smarty Template Primer Tutorial", "PHP date and Time usage summary", "PHP object-oriented Program Design Introductory Course ", PHP string (String) Usage summary," PHP+MYSQL Database operation Introduction Tutorial "and" PHP common database Operation Skills Summary "

I hope this article will help you with the PHP program design based on Laravel framework.

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.