Everything has a life cycle, and when we use any tool, we need to understand how it works so that it works. The same goes for app development. If you understand how it works, you’ll be able to use it with ease.

Before we look at Laravel’s life cycle, let’s review PHP’s life cycle.

PHP life cycle

PHP operating mode

PHP runs in WEB mode and CLI mode.

  1. When we type the PHP command on the terminal, we use CLI mode.
  2. Web mode is used when an incoming request is processed using Nginx or another Web server as host.

The life cycle

When we request a PHP file,PHP switches through five phases of the lifecycle to complete the request:

  1. Module initialization (MINIT), which calls the initialization function of an extension specified in php.ini, such as the mysql extension.

  2. Request initialization (RINIT), that is, a symbol table that initializes the variable name and variable value content needed to execute this script, such as the $_SESSION variable.

  3. Execute the PHP script.

  4. When the Request Shutdown is complete, the RSHUTDOWN method of each module is called sequentially and the unset function is called for each variable, such as the unset $_SESSION variable.

  5. To Shutdown modules, PHP calls each extended MSHUTDOWN method, which is the last chance for each Module to free memory. This means there is no next request.

The WEB mode is similar to the CLI (command line) mode with the following differences:

  1. In CLI mode, each script execution goes through a full 5 cycles, because you don’t get another request after the script is executed.
  2. The WEB pattern may be multithreaded to cope with concurrency, hence the lifecycle1and5It is possible to do it once and repeat it the next time the request comes in2-4In order to save the overhead of system module initialization.

You can see that the PHP life cycle is very symmetrical. Having said all that, to locate where Laravel runs, yes, Laravel only runs the third stage:

PHP life Cycle

role

By understanding this, you can optimize your Laravel code and learn more about Laravel singletons. At least you know that PHP variables are unset at the end of each request, and Laravel’s singleton is only a singleton during a particular request; Your static variables in Laravel also cannot be shared between multiple requests because each request ends with unset. Understanding these concepts is the first and most critical step in writing high-quality code. So keep in mind that PHP is a scripting language, and all variables only take effect on one request and have been reset on the next, unlike Java static variables that have global effects.

Laravel’s life cycle

An overview of the

Laravel’s life cycle starts at public\index.php and ends at public\index.php.

Request process

Here is the full source code for public\index.php, which can be broken down into four steps:

1. require __DIR__.'/.. /bootstrap/autoload.php';

2. $app = require_once __DIR__.'/.. /bootstrap/app.php';
   $kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);

3. $response = $kernel->handle(
      $request = Illuminate\Http\Request::capture()
   );
   $response->send();

4. $kernel->terminate($request.$response);

Copy the code

The following four steps are explained in detail:

Composer automatically loads the required classes

  1. File load Composer generates auto-load Settings, including all of yourcomposer requireRely on.
  2. Generate the Container, the Application instance, and register the core components (HttpKernel, ConsoleKernel, ExceptionHandler) with the Container (for code 2, the Container is important, more on that later).
  3. Handles the request, generates and sends the response (corresponding to code 3, literally 99% of your code is running inside this little Handle method).
  4. The request completes, and the callback (corresponding to code 4, remember terminable middleware? That’s right, that’s where it’s called back).

Laravel request steps

Let’s be more specific:

Step 1: Register to load composer automatically generatedclass loader

Load initializes third-party dependencies.

Step 2: Generate the containerContainer

And register the core components with the container to get the Laravel application instance from the bootstrap/app.php script.

Step 3: This step is the focus, processing the request and generating the send response.

Requests are sent to either the HTTP kernel or the Console kernel, depending on the type of request coming into the application.

Depending on whether the request is made through the browser or the console. In this case, we mainly request through the browser.

The HTTP Kernel inherits from the Illuminate Foundation HTTP Kernel class, which defines an array of bootstrappers classes that run before the request is executed, These bootstrappers configure error handling, logging, detecting the application environment, and other tasks that need to be performed before the request can be processed.

protected $bootstrappers = [
    // Register system environment configuration (.env)
    'Illuminate\Foundation\Bootstrap\DetectEnvironment'.// Register system configuration (config)
    'Illuminate\Foundation\Bootstrap\LoadConfiguration'.// Register log configuration
    'Illuminate\Foundation\Bootstrap\ConfigureLogging'.// Register exception handling
    'Illuminate\Foundation\Bootstrap\HandleExceptions'.// Register the Facade of the service container, which is a class that provides access to objects from the container.
    'Illuminate\Foundation\Bootstrap\RegisterFacades'.// Register the service provider
    'Illuminate\Foundation\Bootstrap\RegisterProviders'.// Register service provider 'boot'
    'Illuminate\Foundation\Bootstrap\BootProviders',];Copy the code

Note the order:

ServiceProviders are provided with Facades instead of ServiceProviders. To register Facades is to register an array of aliases in config\app.php. Cache,DB, and so on are Facades; The ServiceProviders register method is always executed before the boot method. Otherwise, the boot method depends on an unregistered instance.

The HTTP kernel also defines a set of HTTP middleware that all requests go through before processing, which handles reading and writing HTTP sessions, determining whether the application is in maintenance mode, validating CSRF tokens, and so on.

The HTTP kernel’s signature method, Handle, handles a fairly simple logic: get a Request, return a Response, think of the kernel as a big black box representing the entire application, enter an HTTP Request, and return an HTTP Response.

Step 4: Pass the request to the route.

After the Laravel based service is started, the request is passed to the route. The router will distribute requests to the route or controller, running all middleware specified by the route.

Routes are passed through pipelines, but pipelines have a wall that all requests pass through before being passed to routes. This wall is defined in the $middleware array in app\Http\ kernel.php. By default there is only one CheckForMaintenanceMode middleware that detects if your website is temporarily down. This is a global middleware, all requests go through, you can also add your own global middleware.

Then walk through all the registered routes, find the first route that matches first, pass through its routing middleware, enter the controller or closure function, and execute your specific logic code.

So by the time a request reaches your code, Laravel will have done a lot of work, and the request will have gone through a lot of trouble, and those that don’t conform or are malicious will have been quarantined by Laravel.

Process request to response

This article is from: Jane Book

Thanks to author: Summer

Laravel’s life cycle