


Laravel uses Caching to cache data to reduce database query pressure, laravelcaching_PHP tutorial
Laravel uses Caching to cache data to reduce database query pressure, laravelcaching
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程序设计有所帮助。
您可能感兴趣的文章:
- Laravel框架中实现使用阿里云ACE缓存服务
- Laravel中扩展Memcached缓存驱动实现使用阿里云OCS缓存
- 基于laravel制作APP接口(API)
- PHP框架Laravel学习心得体会
- 使用AngularJS和PHP的Laravel实现单页评论的方法
- PHP IDE PHPStorm配置支持友好Laravel代码提示方法
- Laravel 5 框架入门(四)完结篇
- Laravel 5 框架入门(三)
- Laravel 5 框架入门(二)构建 Pages 的管理功能
- Laravel 5 框架入门(一)
- Laravel 5框架学习之用户认证
- Laravel 5框架学习之Eloquent 关系
- Laravel 5框架学习之子视图和表单复用
- Laravel 5框架学习之表单验证
- Laravel 5框架学习之日期,Mutator 和 Scope

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

Key players in HTTP cache headers include Cache-Control, ETag, and Last-Modified. 1.Cache-Control is used to control caching policies. Example: Cache-Control:max-age=3600,public. 2. ETag verifies resource changes through unique identifiers, example: ETag: "686897696a7c876b7e". 3.Last-Modified indicates the resource's last modification time, example: Last-Modified:Wed,21Oct201507:28:00GMT.

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version
Visual web development tools

Dreamweaver CS6
Visual web development tools