This article describes the example of Laravel using Caching to cache data to reduce database query pressure. Share it with everyone for your reference, the details are as follows:
Yesterday I wanted to cache the homepage of my blog to achieve an effect similar to generating a static page cache. I asked everyone in the group how to cache, but they were all very busy and didn’t reply much, so I went to read the documentation myself. , I discovered the Caching part. In fact, I had an impression of it before, but I had no specific contact with it. As the name suggests, it is caching. It must be somewhat related to my needs. I took a closer look and found that it was indeed too powerful. The process was very simple. In a few steps, I modified the homepage, tested it with firebug, and improved the parsing time by dozens of milliseconds. Of course, some people will laugh at whether this is necessary. Isn’t it a pain in the ass? In fact, I think it is necessary. Yes, it’s just that there are not many visitors here (actually no one visits at all, hehe...), and secondly, the queries I do on the homepage are quite few so far, just once, which is to get all the blog posts. If a page There are seven or eight or even more than ten queries in it. I think the effect should be obvious! (Of course, Brother Raymond also mentioned using a more advanced dedicated cache to do it (memcached and the like), this This can only be achieved if you have control over the server and can freely install software or if the server already has these caching mechanisms. My needs are relatively simple and I don’t have the environment to do it, so I won’t consider it here)
Without further ado, let’s get started and talk about my specific needs:
1. Implement data caching on the home page. If there is a cache that has not expired, the database will not be checked. This basically simulates the effect of a static page (of course, it still needs to be processed by PHP)
2. Implement the function of refreshing the specified cache (there is only the home page here, so it only means refreshing the home page cache. I have implemented this function under the admin module
Detailed implementation:
1. Check the documentation and find the module that can help me achieve my needs
I checked the documentation and found out that there is a module called Caching. As the name suggests, it is caching. So if it can help me, let’s see first:
1. http://laravel.com/docs/cache/config Here is the implementation of laravel’s 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 visits your site? What if you could store them for 10 minutes , or even an hour, allowing you to dramatically speed up your application? Laravel's caching makes it simple.
I simply understand it as:
Suppose your app displays the 10 most popular songs voted by users, do you really need to check these 10 songs every time everyone visits your website? If you want to click 10 minutes or one To cache query results every hour to speed up your application, Laravel's caching module can make the job extremely easy.
Well, from this paragraph, I have learned that this completely meets my current needs. Next, I just need to find the corresponding usage methods and APIs, step by step.
2. Learn the corresponding API, etc.
1. Still in the above document, look down and see the following description:
By default, Laravel is 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 simply understand it as:
By default, Laravel uses the file system as the cache driver, which can be used without configuration. The file system driver will store the cached data in the file in the cache directory. If you think it is appropriate, do not If you need to do any other configuration, just start using it.
Of course, this is also in line with my idea. In fact, I just want to cache the page into a static page file. When the user visits again, it will be ok to directly output the cached static page. If you need more advanced requirements, you can also use Other drivers include database drivers, memcached, redis drivers, etc., which are very good and powerful!
2. Next, check the use cases and find out how to use it
The use case documentation is here: http://laravel.com/docs/cache/usage
As you can see, there are methods such as get, put, forever, remember, has, forget, etc. These methods can basically be used "literally", haha
The specific usage documentation has already been explained in detail. I won’t go into details since the usage is clear at a glance. I’ll just explain it in the code
3. Specific implementation
1. The code before my homepage
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, 'post_title' => $p -> post_title, 'post_body' => $p -> post_body ); } return View::make('home.index') -> with('posts', $data); } }
This is the controller on my homepage. It has only one function, which is to get all the blog posts from the blog post table and then output it. Every time someone visits, the table must be checked. If no new blog post is published, the table must be checked. Indeed, there is. A lot of unnecessary expenses
2. The following is the code after my modification:
class Home_Controller extends Base_Controller { public function get_index() { // 添加静态缓存支持 // 如果不存在静态页缓存就立即缓存 if ( !Cache::has('staticPageCache_home') ) { $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', '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_title' => $p -> post_title, 'post_body' => $p -> post_body ); } $res = View::make('home.index') -> with('posts', $data); Cache::forever('staticPageCache_home', $res); } // 返回缓存的数据 return Cache::get('staticPageCache_home'); } }
这里我用到了三个api
1). Cache::has ,这个判断是说如果当前不存在 staticPageCache_home 这个名字的缓存, 就立即去取数据
2). Cache::forever, 这个从用例文档里面可知是"永久缓存"的意思, 因为我一般都是很勤劳的,如果发表了博文,自己再去后台立即刷新一下缓存就好了, 所以不需要设置过期啊失效时间之类的, 当然这个是要按各自的具体需求来的
3). Cache::get , 这句是从缓存里面取出 staticPageCache_home 这个名字的缓存, 然后作为响应内容返回
嗯, 就这么简单, 呵呵, 一个基本的缓存功能就完成了, laravel的确是不错地!
3. 为后台添加刷新缓存功能
还是贴代码吧, 不过也很简单:
// 刷新首页缓存(暂时只支持首页) public function get_refreshcache() { /* @var $GID admin组id */ $GID = 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', '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_title' => $p -> post_title, 'post_body' => $p -> post_body ); } $res = View::make('home.index') -> with('posts', $data); Cache::forever('staticPageCache_home', $res); return '刷新首页缓存成功!'; } return '对不起,只有管理员组才可进行此操作!'; }
我给后台添加了一个项目, 对应这个方法, 方法内容和首页的大同小异, 取数据, 然后Cache::forever 刷新一下缓存,就这么简单,当然了,上面的Auth::user() 判断是个简单的判断,只有管理员组才能进行刷新操作,呵呵
嗯, 全部内容就这么多, 很简单, 欢迎童鞋们拍砖指正!
希望本文所述对大家基于Laravel框架的PHP程序设计有所帮助。