Home  >  Article  >  PHP Framework  >  ThinkPHP6 application initialization (source code analysis)

ThinkPHP6 application initialization (source code analysis)

藏色散人
藏色散人forward
2020-01-30 19:29:363946browse

ThinkPHP6 application initialization (source code analysis)

ThinkPHP6 source code analysis application initialization

App Construct

First let’s take a look at what is done in __construct. Basically any framework 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.

● ThinkPath, rootPath, appPath, runtimePath are set up

● The default service provider is bound, and a total of two are provided, app\Reques and app\ExceptionHandle. In fact, 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;
}

● Load the .env environment variable file

● Load 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 event.php event in the application directory

● Register the service.php service in the application directory

● Load the language pack

● Listen to the AppInit event, you can 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, so 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

● Instantiate the service

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

● If the bind attribute is set, the service instance needs to be bound to the container

● Finally merged into the entire service array and wait for boot

Service startup

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. Let’s talk about RegisterService and BootService here.

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 provides a total of two instructions, 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();
}

For more related ThinkPHP knowledge, please visit ThinkPHP Tutorial!

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

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete