search
HomePHP FrameworkThinkPHPThinkPHP6 source code analysis application initialization

ThinkPHP6 source code analysis application initialization

App Construct

First let’s take a look at what is done in __construct, basically any framework They will do some basic operations here, that is, extend from here.

public function __construct(string $rootPath = '')
{
    $this->thinkPath   = dirname(__DIR__) . DIRECTORY_SEPARATOR;
    $this->rootPath    = $rootPath ? rtrim($rootPath, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR : $this->getDefaultRootPath();
    $this->appPath     = $this->rootPath . 'app' . DIRECTORY_SEPARATOR;
    $this->runtimePath = $this->rootPath . 'runtime' . DIRECTORY_SEPARATOR;
    if (is_file($this->appPath . 'provider.php')) {
        $this->bind(include $this->appPath . 'provider.php');
    }
    static::setInstance($this);
    $this->instance('app', $this);
    $this->instance('think\Container', $this);
}

● Judging from the parameter rootPath of the magic method, it supports customizing the root directory path.

● Set up thinkPath, rootPath, appPath, runtimePath

● Bind the default service provider, providing a total of two, app\Reques and app\ExceptionHandle, actually you use The Request is it. Specifically go to appPath to view

● Set the current container instance APP

● Bind the App($this) instance to the container, respectively app and think\Container

here It should be noted that the App class inherits Container, so it binds its own instance to the container.

It seems that the entire application has been initialized here? Here I need to put part of the content of Request run here, because that is the main initialization work of the framework. I don't think it is reasonable to put this part of the initialization work in Request run.

Main initialization

public function initialize()
{
    $this->initialized = true;
    $this->beginTime = microtime(true);
    $this->beginMem  = memory_get_usage();
    // 加载环境变量
    if (is_file($this->rootPath . '.env')) {
        $this->env->load($this->rootPath . '.env');
    }
    $this->configExt = $this->env->get('config_ext', '.php');
    $this->debugModeInit();
    // 加载全局初始化文件
    $this->load();
    // 加载框架默认语言包
    $langSet = $this->lang->defaultLangSet();
    $this->lang->load($this->thinkPath . 'lang' . DIRECTORY_SEPARATOR . $langSet . '.php');
    // 加载应用默认语言包
    $this->loadLangPack($langSet);
    // 监听AppInit
    $this->event->trigger('AppInit');
    date_default_timezone_set($this->config->get('app.default_timezone', 'Asia/Shanghai'));
    // 初始化
    foreach ($this->initializers as $initializer) {
        $this->make($initializer)->init($this);
    }
    return $this;
}

● Loading the .env environment variable file

● Loading the configuration file and files within the application

● Load common.php

in the application ● Load the helper function in helper.php

● in the thinkPath directory● Load the configuration file

● Load the event in the application directory. php event

● Register the service.php service in the application directory

● Load the language pack

● Listen to the AppInit event and use this event to do some pre-request work

● Set time zone

● Inject all services and start the service

Service registration

During the initialization process, perform service registration, then What does service registration do? How to use the service?

public function register($service, bool $force = false)
{
    $registered = $this->getService($service);
    if ($registered && !$force) {
        return $registered;
    }
    if (is_string($service)) {
        $service = new $service($this);
    }
    if (method_exists($service, 'register')) {
        $service->register();
    }
    if (property_exists($service, 'bind')) {
        $this->bind($service->bind);
    }
    $this->services[] = $service;
}

● Whether the service has been registered, if you need to force re-registration

● Instantiation of the service

● If the register method is implemented, you need to execute the register method

● If the bind attribute is set, you need to bind the service instance to the container

● Finally merge it into the entire service array and wait for the boot

service to start

Currently, there are only the following three services during initialization. In the $this->initializers array,

foreach ($this->initializers as $initializer) {
        $this->make($initializer)->init($this);
}

these three services are:

think\initializer\BootService
think\initializer\Error
think\initializer\RegisterService

● Error service is Used to handle framework exceptions and errors

● RegisterService literally means to register services

● BootService is to enable services

Error handling will be discussed later, here it is said Let's look at RegisterService and BootService.

When RegisterService is made from Container

There is a hidden static method make. Every time the instance object is made from Container for the first time, the make method will be executed. Of course, it must first be You implement the method.

The Init method will then be executed. When you enter RegisterService, you will see this method. The method content is as follows:

public function init(App $app)
{
    $file = $app->getRootPath() . 'runtime' . DIRECTORY_SEPARATOR . 'services.php';
    $services = $this->services;
    if (is_file($file)) {
        $services = array_merge($services, include $file);
    }
    foreach ($services as $service) {
        if (class_exists($service)) {
            $app->register($service);
        }
    }
}

This method is very strange, a little different from what I imagined. The service is obtained directly from the runtime directory, not from service.php in the config directory. Why is this so? Due to the development of composer, the TP framework can also provide automatic discovery of packages, which also proves that the development team is constantly moving closer to the community. Let’s take a look at how this is achieved.

Because this is all due to composer, so take a look at composer.json under rootPath. Go to the bottom and you will find the following configuration

"scripts": {
    "post-autoload-dump": [
        "@php think service:discover",
        "@php think vendor:publish"
    ]
}

From the configuration point of view, the framework A total of two instructions are provided, service:discover and vendor:publish. I won’t go into the specific implementation here. You only need to know that package discovery is implemented by service:discover.

Also, three services are injected by default here.

PaginatorService::class,
ValidateService::class,
ModelService::class,

Finally let’s take a look at BootService. This is very simple. From the naming point of view, it is not difficult to see that the following is the code to start the service normally, but what needs to be explained here is that the boot method must be implemented in the service class before it can be started.

public function init(App $app)
{
    $app->boot();
}

The above is the initialization of the entire application, the specific details will be discussed later.

This article comes from the ThinkPHP framework technical article column: http://www.php.cn/phpkj/thinkphp/

The above is the detailed content of ThinkPHP6 source code analysis application initialization. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:learnku. If there is any infringement, please contact admin@php.cn delete
What Are the Key Features of ThinkPHP's Built-in Testing Framework?What Are the Key Features of ThinkPHP's Built-in Testing Framework?Mar 18, 2025 pm 05:01 PM

The article discusses ThinkPHP's built-in testing framework, highlighting its key features like unit and integration testing, and how it enhances application reliability through early bug detection and improved code quality.

How to Use ThinkPHP for Building Real-Time Stock Market Data Feeds?How to Use ThinkPHP for Building Real-Time Stock Market Data Feeds?Mar 18, 2025 pm 04:57 PM

Article discusses using ThinkPHP for real-time stock market data feeds, focusing on setup, data accuracy, optimization, and security measures.

What Are the Key Considerations for Using ThinkPHP in a Serverless Architecture?What Are the Key Considerations for Using ThinkPHP in a Serverless Architecture?Mar 18, 2025 pm 04:54 PM

The article discusses key considerations for using ThinkPHP in serverless architectures, focusing on performance optimization, stateless design, and security. It highlights benefits like cost efficiency and scalability, but also addresses challenges

How to Implement Service Discovery and Load Balancing in ThinkPHP Microservices?How to Implement Service Discovery and Load Balancing in ThinkPHP Microservices?Mar 18, 2025 pm 04:51 PM

The article discusses implementing service discovery and load balancing in ThinkPHP microservices, focusing on setup, best practices, integration methods, and recommended tools.[159 characters]

What Are the Advanced Features of ThinkPHP's Dependency Injection Container?What Are the Advanced Features of ThinkPHP's Dependency Injection Container?Mar 18, 2025 pm 04:50 PM

ThinkPHP's IoC container offers advanced features like lazy loading, contextual binding, and method injection for efficient dependency management in PHP apps.Character count: 159

How to Use ThinkPHP for Building Real-Time Collaboration Tools?How to Use ThinkPHP for Building Real-Time Collaboration Tools?Mar 18, 2025 pm 04:49 PM

The article discusses using ThinkPHP to build real-time collaboration tools, focusing on setup, WebSocket integration, and security best practices.

What Are the Key Benefits of Using ThinkPHP for Building SaaS Applications?What Are the Key Benefits of Using ThinkPHP for Building SaaS Applications?Mar 18, 2025 pm 04:46 PM

ThinkPHP benefits SaaS apps with its lightweight design, MVC architecture, and extensibility. It enhances scalability, speeds development, and improves security through various features.

How to Build a Distributed Task Queue System with ThinkPHP and RabbitMQ?How to Build a Distributed Task Queue System with ThinkPHP and RabbitMQ?Mar 18, 2025 pm 04:45 PM

The article outlines building a distributed task queue system using ThinkPHP and RabbitMQ, focusing on installation, configuration, task management, and scalability. Key issues include ensuring high availability, avoiding common pitfalls like imprope

See all articles

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 agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.