Home > Article > PHP Framework > Detailed explanation and cases: Introduction to the life cycle of Laravel requests
This article brings you relevant knowledge about laravelThe request declaration cycle. The request life cycle has different terms, such as autoloader, kernel, service provider, scheduling request and routing, etc. ,I hope everyone has to help.
Laravel is a powerful PHP framework. When you learn the laravel framework, the Laravel request lifecycle is the best starting point. This article will introduce what happens between the receipt of an HTTP request and the response in Laravel. An in-depth study of the request lifecycle will help us understand Laravel structure. (Based on Laravel 8)
There are different terms for the request lifecycle, such as autoloader, kernel, service provider, dispatch request and routing, etc. Once you understand all the terminology in detail, you will have more understanding of the framework and can extend it with different features as you like.
Load project dependencies and create a Laravel application instance
Laravel The entry point for all requests to the application is the public/index.php
file. All requests are directed to this file by your web server (Apache/Nginx) configuration. That index.php file doesn't contain much code. Instead, it is the starting point for loading the rest of the frame.
# 1、加载项目依赖require __DIR__.'/../vendor/autoload.php'; $app = require_once __DIR__.'/../bootstrap/app.php';
The index.php
file will load the autoloader definition generated by Composer and then retrieve the instance of the Laravel application from bootstrap/app.php
.
bootstrap/app.php:
<?php # 2、创建应用实例 $app = new Illuminate\Foundation\Application( $_ENV['APP_BASE_PATH'] ?? dirname(__DIR__) ); # 3、完成内核绑定 $app->singleton( Illuminate\Contracts\Http\Kernel::class, App\Http\Kernel::class ); $app->singleton( Illuminate\Contracts\Console\Kernel::class, App\Console\Kernel::class ); $app->singleton( Illuminate\Contracts\Debug\ExceptionHandler::class, App\Exceptions\Handler::class ); return $app;
After that, it will bootstrap the Laravel framework to use and generate an application instance.
public/index.php:
# 4、接收请求并响应$kernel = $app->make(Kernel::class);// 处理请求$response = tap($kernel->handle( // 创建请求实例 $request = Request::capture()// 发送响应))->send();$kernel->terminate($request, $response);
Once the application instance is generated, incoming requests will be handled by the kernel.
Next, the incoming request is sent to the HTTP core or the Console core, depending on the type of request entering the application. These two cores act as the central location through which all requests flow. For now, let's just focus on the HTTP kernel, which is located in app/Http/Kernel.php
.
The HTTP kernel extends the Illuminate\Foundation\Http\kernel
class, which defines an array of bootstrappers that will be run before executing the request. These bootstraps are used to configure exception handling, configure logging, detect the application environment, and perform other tasks that need to be completed before the request is actually processed. Normally, you don't need to worry about these configurations.
The HTTP kernel also defines a list of HTTP middlewares that all requests must pass through before being processed by the application. These middlewares handle reading and writing HTTP sessions, determining whether the application is in maintenance mode, validating CSRF tokens, and more. We will discuss this in detail next.
The signature of the HTTP kernel's handle method is very simple: it receives the Request interface and returns the Response interface. Think of the kernel as a big black box that represents the entire application. Give it an HTTP request and it will return an HTTP response.
The HTTP kernel also loads service providers by configuring middleware and other functions.
One of the most important kernel boot operations is loading service providers
for the application. All service providers for the application are in the providers
array in config/app.php
.
Laravel will iterate through this list of providers and instantiate each one of them. After a provider is instantiated, the register
method is called on all providers. Then, once all providers are registered, the boot
method is called on each provider.
The service provider is responsible for bootstrapping all the different components of the framework, such as database, queue, validation and routing components. Basically, every major feature provided by Laravel is bootstrapped and configured by a service provider. Service providers are the most important part of the entire Laravel bootstrapping process due to the many features provided by their bootstrapping and configuration framework.
You may be wondering why the register method of each service provider is called before calling the boot
method on any service provider. The answer is simple. By first calling each service provider's register method, the service provider may rely on each container binding being registered and available when the boot method is executed.
Service providers are the key to bootstrapping your Laravel application. The application instance is created, the service provider is registered, and the request is handed to the bootstrapping application. It's really that simple!
Having a firm grasp of how Laravel applications are built and bootstrapped through service providers is extremely valuable. Your application's default service providers are stored in the app/Providers
directory.
By default, AppServiceProvider is empty. This procedure is a good place to add your application's own bootstrap and service container bindings. For large applications, you may want to create multiple service providers, each providing more granular guidance for the specific services your application uses.
Once the application is bootstrapped and all service providers are registered and bootstrapped, requests are handed over to the router for dispatch.
One of the most important service providers in an application is App\Providers\RouteServiceProvider
. This service provider loads route files contained in the application's routes
directory.
The router sends the request to a route or controller and runs any route-specific middleware.
Middleware provides a convenient mechanism for filtering or inspecting HTTP requests entering an application. For example, Laravel includes a middleware that verifies that users of your application are authenticated. If the user is not authenticated, the middleware redirects the user to the login page. However, if the user is authenticated, the middleware will allow the request further into the application. Some middlewares are assigned to all routes in the application, such as those defined in the $middleware
attribute of the HTTP core, while some are assigned only to specific routes or groups of routes. You can learn more about middleware by reading the complete middleware documentation.
If the request passes all matching route assigned middleware, direct the HTTP request to the controller or directly return the view or response by omitting the controller
Controllers app/Http/Controllers/
Perform specific actions and send data to the view.
Views resources/views/
Format data appropriately to provide an HTTP response.
Once a route or controller method returns a response, that response is returned through the route's middleware, giving the application the opportunity to modify or inspect the outgoing response.
Normally, you won't just return a simple string or array from a routing operation. Instead, a complete Illuminate\Http\Response
instance or view is returned.
Response instances are derived from the Symfony\Component\Http\Foundation\Response
class, which provides many methods for constructing HTTP responses.
Finally, once the response is passed back through the middleware, the HTTP kernel's handle method returns the response object, and the index.php
file calls the send method on the returned response. The send method sends the response content to the user's web browser.
At this point, we have completed all the steps of the entire Laravel request life cycle!
[Related recommendations: laravel video tutorial]
The above is the detailed content of Detailed explanation and cases: Introduction to the life cycle of Laravel requests. For more information, please follow other related articles on the PHP Chinese website!