Table of Contents
runWithRequest () method
Home PHP Framework ThinkPHP Parsing ThinkPHP6 application initialization

Parsing ThinkPHP6 application initialization

Jul 13, 2021 pm 01:51 PM
php thinkphp6

runWithRequest () method

In the run() method of the Http class , after obtaining the instance of the think\\Request class, the program then executes $response = $this->runWithRequest(request);. Among them, the first few lines of the runWithRequest() method are as follows:

protected function runWithRequest(Request $request)
{
    $this->initialize();

    // 加载全局中间件
    $this->loadMiddleware();
    .
    .
    .
Copy after login

The first line of this method executes $this->initialize(); to initialize the application , let’s analyze this initialization operation in detail.
Http The initialize() method of the class:

protected function initialize()
{
    //如果还未初始化,则初始化之
    if (!$this->app->initialized()) {
        $this->app->initialize();
    }
}
Copy after login

actually calls the initialize()# of the App class ## method. Code of this method:

public function initialize()
{
    // 设置应用状态为已经初始化
    $this->initialized = true;

    //记录开始时间
    $this->beginTime = microtime(true);
    //记录起始内存使用量
    $this->beginMem  = memory_get_usage();

    // ==( A )== 加载环境变量
    // $this->env跟前面的(new App())->http和$this->config都是同样的套路
    if (is_file($this->rootPath . '.env')) {
        $this->env->load($this->rootPath . '.env');
    }
    //设置配置文件后缀
    $this->configExt = $this->env->get('config_ext', '.php');
    // ==( B )== 设置调试模式
    $this->debugModeInit();

    // ==( C )== 加载应用文件和配置等操作
    $this->load();

    // 加载框架默认语言包
    $langSet = $this->lang->defaultLangSet();
    // 框架目录下对应的语言包
    // 比如:D:\dev\tp6\vendor\topthink\framework\src\lang\zh-cn.php
    $this->lang->load($this->thinkPath . 'lang' . DIRECTORY_SEPARATOR . $langSet . '.php');

    // 加载应用默认语言包
    // 这个会扫描「app/lang」里面,对应语言包文件夹的所有「.php」文件
    // 比如,app/lang/zh-cn/* 下的所有文件
    // 然后加载解析
    $this->loadLangPack($langSet);

    // 监听AppInit
    $this->event->trigger('AppInit');

    // 设置时区
    date_default_timezone_set($this->config->get('app.default_timezone', 'Asia/Shanghai'));

    // ==( D )== 初始化
    // 初始化错误和异常处理、注册系统服务和初始化系统服务
    foreach ($this->initializers as $initializer) {
        $this->make($initializer)->init($this);
    }

    return $this;
}
Copy after login
The initialization of the application does a lot of operations. Its main operations are: loading environment variables, loading configuration files, loading language packs, monitoring AppInit, and initialization of classes contained in the initializers array.

(A) Load environment variables

Corresponding statement:

$this->env->load($this->rootPath . '.env');, among them, $this->env, the principle is the same as the previous (new App())->http (see the first article), it can be obtained Instance of class \think\Env. After obtaining the Env class instance, call the load() method, and the passed-in parameter is the address of the .env file. The load() method is implemented as follows:

public function load(string $file): void
{
    $env = parse_ini_file($file, true) ?: [];
    $this->set($env);
}
Copy after login
After this method reads the value of the

.env file, it calls the set() method to The configuration is saved in the $data member variable of the Env class. set() Method code:

public function set($env, $value = null): void
{
    if (is_array($env)) {
        //全部KEY转为大写字母
        $env = array_change_key_case($env, CASE_UPPER);

        foreach ($env as $key => $val) {
            //有二级配置的,转为KEY1_KEY2 => $v 的形式
            if (is_array($val)) {
                foreach ($val as $k => $v) {
                    $this->data[$key . '_' . strtoupper($k)] = $v;
                }
            } else {
                $this->data[$key] = $val;
            }
        }
        //ENV的值不是数组的情况
    } else {
        $name = strtoupper(str_replace('.', '_', $env));

        $this->data[$name] = $value;
    }
}
Copy after login
The value read from

.env is probably like this:
Parsing ThinkPHP6 application initialization

$this->set($env) What you get after that is probably like this:

Parsing ThinkPHP6 application initialization

(B) Debug mode setting

$this->debugModeInit() See the comments for details on the operating principle.

protected function debugModeInit(): void
{
    // 应用调试模式
    if (!$this->appDebug) {
        $this->appDebug = $this->env->get('app_debug') ? true : false;
        // 关闭错误显示
        ini_set('display_errors', 'Off');
    }
    // 如果不是命令行模式
    if (!$this->runningInConsole()) {
        // 重新申请一块比较大的buffer
        // php缓冲控制
        // 参考:https://www.php.net/manual/en/ref.outcontrol.php
        // https://www.cnblogs.com/saw2012/archive/2013/01/30/2882451.html
        // 新版PHP默认开启缓冲区ob_start(),ob_get_level() == 1
        if (ob_get_level() > 0) {
            // 相当于ob_get_contents() 和 ob_clean()
            // 获取缓冲区内容并删除缓冲区内容
            $output = ob_get_clean();
        }
        // 开启新的缓冲区控制
        ob_start();
        if (!empty($output)) {
            // 由于开启了新的缓冲区控制,
            // 这里不会直接输出$output
            // 而是等到依次执行了ob_flush()和flash()之后才将内容输出到浏览器
            echo $output;
        }
    }
}
Copy after login
It should be noted that there seems to be a bug here. You should execute

$this->appDebug = $this->env->get('app\_debug') ? true : false; Get the configuration of debug mode, and then judge: if(!$this->appDebug).

(C) Load application files and configuration operations

Next execute

$this->load();, the "load" method is implemented as follows:

protected function load(): void
{
    $appPath = $this->getAppPath();

    // 加载「app」目录下的「common.php」文件
    if (is_file($appPath . 'common.php')) {
        include_once $appPath . 'common.php';
    }
    // 加载核心目录下的「helper.php」文件
    // 可以看到,这里的加载顺序:先「common.php」,后「helper.php」
    // 且「helper.php」中的函数包裹在「if (!function_exists('xxx'))」下
    // 所以可以在「common.php」文件中覆盖系统定义的助手函数
    include_once $this->thinkPath . 'helper.php';

    $configPath = $this->getConfigPath();

    $files = [];

    // glob的作用是扫描给定路径模式下的文件,非常好用
    // 这里扫描「config」目录下的所有「.php」文件
    if (is_dir($configPath)) {
        $files = glob($configPath . '*' . $this->configExt);
    }

    foreach ($files as $file) {
        // $this->config 还是同样的套路获得了「Config」类的实例
        // 「load」的第二个参数为一级配置名,这里传入一个文件名,所有文件名作为一级配置
        // 比如「app.php」配置文件,一级配置为「app」
        // 在 「Config」类作用域下的操作:
        // 「load」加载文件后,通过「parse」方法解析文件内容
        // 最后,通过「set」方法将所有配置合并了「config」成员变量
        $this->config->load($file, pathinfo($file, PATHINFO_FILENAME));
    }

    // 加载「app」目录下的「event.php」文件
    if (is_file($appPath . 'event.php')) {
        $this->loadEvent(include $appPath . 'event.php');
    }
    // 注册自定义的服务
    if (is_file($appPath . 'service.php')) {
        $services = include $appPath . 'service.php';
        foreach ($services as $service) {
            $this->register($service);
        }
    }
}
Copy after login
It is worth mentioning that the program loads "common.php" first and then "helper.php", and the functions in "helper.php" are wrapped in "if (!function_exists ('xxx') )", so if we need to, we can override the system-defined helper function in the "common.php" file.

In addition to loading these two files, this method also scans all configuration files in the "config" directory and loads them into the

$config of the Config class Member variables load the "event.php" file in the "app" directory, and load and register custom services.

(D) Initialization error and exception handling, registration of system services and initialization of system services

Then, look at the last paragraph of the initialization function:

foreach ($this->initializers as $initializer) {
    $this->make($initializer)->init($this);
}
Copy after login
These lines of code do More operations: Instantiate the classes contained in it separately, and then call its "init" method.

initializers The values ​​of the array are as follows:

protected $initializers = [
    Error::class,  //错误处理类
    RegisterService::class, //注册系统服务类
    BootService::class,  //启动系统服务
];
Copy after login
Skip the system error handling class and look at the registration system service class first. It is worth noting that this class has a member variable:

protected $services = [
    PaginatorService::class,
    ValidateService::class,
    ModelService::class,
];
Copy after login
contains three core system services. In its

init method, these services are registered to the system service and merged with the previous custom service. Its main implementation code is:

foreach ($services as $service) {
    if (class_exists($service)) {
        // 注册到系统服务
        $app->register($service);
    }
}
Copy after login
The last instantiation is to start the system service class , the

init method of this class only calls the boot method of the App class. The function of this method is to initialize each system service, that is, to call each service The boot method. The startup system service class is implemented as follows:

class BootService
{
    public function init(App $app)
    {
        $app->boot();
    }
}
Copy after login

App class’s boot method:

public function boot(): void
{
    array_walk($this->services, function ($service) {
        $this->bootService($service);
    });
}
Copy after login
The key is

bootService Method:

public function bootService($service)
{
    if (method_exists($service, 'boot')) {
        return $this->invoke([$service, 'boot']);
    }
}
Copy after login
This method calls the

boot method of each service separately to initialize the registered service. As you can see from the above code, there are three sources of services registered by the system:

    The system comes with it, such as
  1. PaginatorService, ValidateService , ModelService;
  2. It is customized in the "service.php" file in the app directory; it is defined in the "service.php" file in the
  3. vendor directory.
After initialization, the instance of the "App" class probably looks like this:

Parsing ThinkPHP6 application initialization

The above is the detailed content of Parsing ThinkPHP6 application initialization. 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

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks 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)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

See all articles