Improve Laravel application performance
Using Laravel for development is an efficient and pleasant experience.
Often, when you are ready to deploy an application, you may realize that the application may not perform well in a real environment.
What needs to be understood is that there is no silver bullet. By trying to get all the optimizations right for every detail of your app, it might get slower, but using these tips will get you just right.
Cache configuration file
Laravel's configuration items are distributed in dozens of configuration files, and it consumes performance to import each file including
in each request. . In order to merge all configuration files into one, you can use:
php artisan config:cache
Remember that modifying the configuration file will not affect the existing configuration file cache. To refresh the cache, repeat the above command. If you want to clear the cache completely, execute:
php artisan config:clear
Route Cache
In laravel, routing also requires expensive overhead. Cache the routes.php file with:
php artisan route:cache
Please note that it does not work with closures. If you are using closures, this is a good opportunity to move them into the controller, as the artisan command will throw an exception when trying to compile the path bound to the closure instead of the correct controller method.
Same as configuring the cache, any changes to routes.php will have no impact. To refresh the cache, run the command above every time you change the path file. To completely clean the routing cache, run the following command:
php artisan route:clear
Class map loading optimization
In a medium-sized project, it is normal for hundreds of PHP source files to exist, due to good According to the programming habits, we will separate the code, and each php file has its own responsibilities. Of course, this is not without its drawbacks. Laravel must load these hundreds of files for every request, which is a very performance-consuming thing.
Therefore, a better way is to declare which files need to be loaded every time the user requests (such as service providers, middleware, etc.), and then write these files that need to be loaded each time. In the same file, reduce the number of include files.
This is similar to javascript merging files into one without difference (webpack, gulp), which will reduce browser and server requests.
If you need to add other source files, you can declare them in the files key of config/compile.php.
After you set the files that need to be loaded for each request, they will be written to the same file, reducing the performance consumption of loading files
php artisan optimize --force
Optimize the automatic loading of composer
This applies not only to laravel but to any application using composer.
I'll first explain how the PSR-4 autoloader works, and then show you what commands you should run to optimize it. If you are not interested in understanding how composer works, I recommend skipping directly to the paragraph about console commands.
When you request the App\Controllers\AuthController class from compsoser, it first searches the class map for a direct association. classmap is a 1 to 1 associative array of classes and files. Of course, since you didn't manually add the Login class and its related files to the class map, composer will continue to search in the namespace.
Because App is a PSR-4 namespace that comes with Laravel by default and is associated with the app/ folder, composer will Try converting PSR-4 class names to file names using basic string manipulation procedures. Finally, it guesses that App\Controllers\AuthController must be in the AuthController.php file, which is located in the Controllers/ folder, which, coincidentally, It happens to be located in the namespace folder, i.e. app/.
All this hard work just to get the App\Controllers\AuthController class present in the app/Controllers/AuthController.php file. In order for composer to scan the entire application and create a direct 1-to-1 association of classes and files, run the following command:
composer dumpautoload -o
Remember, if you have already run php artisan optimize --force, then you don't have to run this function again. Because the optimize command already tells composer to create an optimized autoloader.
JIT compiler (just-in-time compiler)
PHP is not naturally understood by computers. You can't compile it to bytecode and have the computer run it. PHP must go through an intermediary, such as the Zend engine, which interprets the PHP file and executes the corresponding C routine. As you can imagine, it's slow. Every time your server executes a PHP file, it must convert it into tokens - this process is done and interpreted by the AST parser. Unfortunately, the parser has to compile the PHP file every time, even if it gets the same result every time.
To make your application faster, you need a compile once, run for life approach, and that's what a JIT compiler does.
对于 Laravel 所推荐使用的 JIT 编译器是 HHVM,由 Facebook 创立并广泛使用。Wikipedia、Etsy 和其他上千项目也在使用它。
使用更快的缓存和会话驱动
将 session 保存在文件中是种足够快速而又优雅的方法,自 PHP 开始的时代就在这样做了。但是如果你追求性能,那么文件系统就是你需要注意的一件事,因为它很慢。一种更好的做法是将 cache 和 session 存储在内存中,因为它提供了一种高效读写数据的方式。幸运的是,laravel 支持一些基于内存的 cache 和 session 驱动。
我的建议是使用 memcached 作为 cache 和 session 的驱动,但你可以选择任何你喜欢的,只要它是基于内存工作的。
要更改 session 驱动,需要检查以下文件中「driver」项:
app/config/session.php
要更改 cache 驱动,需要检查以下文件中「driver」项:
app/config/cache.php
不要低估通过优化查询语句带来的查询速度的提升
就像你看到的,大部分优化都是在不同的层面使用缓存。但当面临数据库优化时,你不应该依赖缓存。缓存应是优化查询的最后手段。
缓存查询结果
MySQL 不会替你做这件事,也不如你自己做的好。当然了你肯定不会把应用中每个查询的结果都做缓存,看看数据统计,在应用程序中那些高频率的查询语句,它们真的有必要被频繁地执行?每 15 分钟运行一次然后把相同的结果提供给用户
不是更好吗?
在查询构造器中移除了 removing
方法是件好事(它曾经是个很好的功能,但不够好 - 人们似乎高估了它的作用)。然后你可以更多地使用 Cache::remember
方法,就像这样:
$posts = Cache::remember('index.posts', 30, function() { return Post::with('comments', 'tags', 'author', 'seo')->whereHidden(0)->get(); });
更多Laravel相关技术文章,请访问Laravel教程栏目进行学习!
The above is the detailed content of Improve Laravel application performance. For more information, please follow other related articles on the PHP Chinese website!

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

When developing websites using CraftCMS, you often encounter resource file caching problems, especially when you frequently update CSS and JavaScript files, old versions of files may still be cached by the browser, causing users to not see the latest changes in time. This problem not only affects the user experience, but also increases the difficulty of development and debugging. Recently, I encountered similar troubles in my project, and after some exploration, I found the plugin wiejeben/craft-laravel-mix, which perfectly solved my caching problem.

Want to learn the Laravel framework, but suffer from no resources or economic pressure? This article provides you with free learning of Laravel, teaching you how to use resources such as online platforms, documents and community forums to lay a solid foundation for your PHP development journey from getting started to master.

Laravel provides a comprehensive Auth framework for implementing user login functions, including: Defining user models (Eloquent model), creating login forms (Blade template engine), writing login controllers (inheriting Auth\LoginController), verifying login requests (Auth::attempt) Redirecting after login is successful (redirect) considering security factors: hash passwords, anti-CSRF protection, rate limiting and security headers. In addition, the Auth framework also provides functions such as resetting passwords, registering and verifying emails. For details, please refer to the Laravel documentation: https://laravel.com/doc

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

The Laravel framework has built-in methods to easily view its version number to meet the different needs of developers. This article will explore these methods, including using the Composer command line tool, accessing .env files, or obtaining version information through PHP code. These methods are essential for maintaining and managing versioning of Laravel applications.

In the Laravel framework version selection guide for beginners, this article dives into the version differences of Laravel, designed to assist beginners in making informed choices among many versions. We will focus on the key features of each release, compare their pros and cons, and provide useful advice to help beginners choose the most suitable version of Laravel based on their skill level and project requirements. For beginners, choosing a suitable version of Laravel is crucial because it can significantly impact their learning curve and overall development experience.

Laravel and ThinkPHP are both popular PHP frameworks and have their own advantages and disadvantages in development. This article will compare the two in depth, highlighting their architecture, features, and performance differences to help developers make informed choices based on their specific project needs.
