Table of Contents
Life cycle of PHP
PHP running mode
Life cycle
Function
Laravel’s life cycle
Overview
首先 Bootstrap 检测环境,加载 bootstrapper数组中的一些配置
第一堵墙,全局中间件,默认为 CheckForMaintenanceMode
然后遍历所有注册的路由,找到最先符合的第一个路由
第二堵墙,通过该路由的中间件(组)
Home PHP Framework Laravel A preliminary understanding of the life cycle in Laravel

A preliminary understanding of the life cycle in Laravel

Sep 07, 2021 pm 07:49 PM
laravel php life cycle

The tutorial column of Laravel will give you a preliminary understanding of the life cycle in Laravel. I hope it will be helpful to friends in need!

A preliminary understanding of the life cycle in Laravel

Life cycle of PHP

PHP running mode

Two types of PHP running The modes are WEB mode and CLI mode.

  • When we type the php command in the terminal, we are using the CLI mode.

  • When using Nginx or another web server as the host to handle an incoming request, the WEB mode is used.

Life cycle

When we request a php file, PHP will undergo 5 stages of life cycle switching in order to complete the request. :

Module initialization (MINIT), that is, calling the extended initialization function specified in php.ini to perform initialization work, such as mysql extension.

Request initialization (RINIT), which is to initialize the symbol table of variable names and variable value contents required to execute this script, such as the $_SESSION variable.

Execute the PHP script.

After the request processing is completed (Request Shutdown), call the RSHUTDOWN method of each module in order, and call the unset function for each variable, such as unset $_SESSION variable.

When closing the module (Module Shutdown), PHP calls the MSHUTDOWN method of each extension. This is the last opportunity for each module to release memory. This means there is no next request.

WEB mode is very similar to CLI (command line) mode. The difference is:

CLI mode will go through a complete 5 cycles each time the script is executed, because there will be no next request; In order to cope with concurrency, the WEB mode may use multi-threading, so life cycles 1 and 5 may only be executed once, and life cycles 2-4 will be repeated when the next request comes, thus saving the overhead caused by system module initialization. It can be seen that the PHP life cycle is very symmetrical. Having said so much, it is to locate where Laravel is running. Yes, Laravel only runs in the third stage:

A preliminary understanding of the life cycle in Laravel

Function

Understand these, you can optimize your Laravel code and have a deeper understanding of Laravel's singleton (single case). At least you know that after each request ends, PHP variables will be unset. Laravel's singleton is only a singleton during a certain request; your static variables in Laravel cannot be shared between multiple requests, because each request It will be unset at the end. Understanding these concepts is the first and most critical step to writing high-quality code. So remember, PHP is a scripting language, and all variables will only take effect in this request and will be reset on the next request, unlike Java static variables that have global effects.

Laravel’s life cycle

Overview

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

A preliminary understanding of the life cycle in Laravel

The following is the entire source code of public\index.php. More specifically, it can be divided 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 after login

The following is a detailed explanation of the four steps. yes: Composer automatically loads the required classes

file to load the auto-loading settings generated by composer, including all your composer require dependencies.

Generate container Container, Application instance, and register core components (HttpKernel, ConsoleKernel, ExceptionHandler) with the container (corresponding to code 2, the container is very important, and will be explained in detail later).

Process the request, generate and send the response (corresponding to code 3, it is no exaggeration to say that 99% of your code runs in this small handle method).

The request ends and a callback is performed (corresponding to code 4, do you remember the terminating middleware? Yes, it is called back here).

A preliminary understanding of the life cycle in Laravel

We might as well go into more detail:

Step 1: Register and load the class loader automatically generated by composer It is to load and initialize third-party dependencies.

Step 2: Generate container Container And registering core components with the container is to obtain the Laravel application instance from the bootstrap/app.php script.

The third step: This step is the focus, processing the request and generating a response. Requests are sent to the HTTP core or the Console core, depending on the type of request coming into the application.

Depends on whether the request is through the browser or the console. Here we mainly request through the browser. The logic of handle processing, the iconic method of the HTTP kernel, is quite simple: get a Request, return a Response, imagine the kernel as a big black box representing the entire application, input an HTTP request, and return an HTTP response.

首先 Bootstrap 检测环境,加载 bootstrapper数组中的一些配置

HTTP 内核继承自 Illuminate\Foundation\Http\Kernel 类,该类定义了一个 bootstrappers 数组,这个数组中的类在请求被执行前运行,这些 bootstrappers 配置了错误处理、日志、检测应用环境以及其它在请求被处理前需要执行的任务。

protected $bootstrappers = [
    //注册系统环境配置 (.env)
    'Illuminate\Foundation\Bootstrap\DetectEnvironment',
    //注册系统配置(config)
    'Illuminate\Foundation\Bootstrap\LoadConfiguration',
    //注册日志配置
    'Illuminate\Foundation\Bootstrap\ConfigureLogging',
    //注册异常处理
    'Illuminate\Foundation\Bootstrap\HandleExceptions',
    //注册服务容器的门面,Facade 是个提供从容器访问对象的类。
    'Illuminate\Foundation\Bootstrap\RegisterFacades',
    //注册服务提供者
    'Illuminate\Foundation\Bootstrap\RegisterProviders',
    //注册服务提供者 `boot`
    'Illuminate\Foundation\Bootstrap\BootProviders',
];
Copy after login

注意顺序:

Facades 先于ServiceProviders,Facades也是重点,后面说,这里简单提一下,注册 Facades 就是注册 config\app.php中的aliases 数组,你使用的很多类,如Auth,Cache,DB等等都是Facades;而ServiceProviders的register方法永远先于boot方法执行,以免产生boot方法依赖某个实例而该实例还未注册的现象。HTTP 内核还定义了一系列所有请求在处理前需要经过的 HTTP 中间件,这些中间件处理 HTTP 会话的读写、判断应用是否处于维护模式、验证 CSRF 令牌等等。

第一堵墙,全局中间件,默认为 CheckForMaintenanceMode

在Laravel基础的服务启动之后,就要把请求传递给路由了。路由器将会分发请求到路由或控制器,同时运行所有路由指定的中间件。

传递方式: 传递给路由是通过 Pipeline(管道)来传递的,但是Pipeline有一堵墙,在传递给路由之前所有请求都要经过,这堵墙定义在app\Http\Kernel.php中的$middleware数组中,没错就是中间件,默认只有一个CheckForMaintenanceMode中间件,用来检测你的网站是否暂时关闭。这是一个全局中间件,所有请求都要经过,你也可以添加自己的全局中间件。

然后遍历所有注册的路由,找到最先符合的第一个路由

然后遍历所有注册的路由,找到最先符合的第一个路由,

第二堵墙,通过该路由的中间件(组)

经过该路由中间件,进入到控制器或者闭包函数,执行你的具体逻辑代码。

所以,当请求到达你写的代码之前,Laravel已经做了大量工作,请求也经过了千难万险,那些不符合或者恶意的的请求已被Laravel隔离在外。

A preliminary understanding of the life cycle in Laravel

原文地址:https://juejin.cn/post/6992208648575385607

作者:卡二条

相关推荐:最新的五个Laravel视频教程

The above is the detailed content of A preliminary understanding of the life cycle in Laravel. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

How to get the return code when email sending fails in Laravel? How to get the return code when email sending fails in Laravel? Apr 01, 2025 pm 02:45 PM

Method for obtaining the return code when Laravel email sending fails. When using Laravel to develop applications, you often encounter situations where you need to send verification codes. And in reality...

See all articles