Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of loading process of TP5 Framework from Import to output Interface

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail the example analysis of the loading process of the TP5 framework from import to output interface. The editor thinks it is very practical, so I share it with you for reference. I hope you can get something after reading this article.

Install ThinkPHP

How to install, I will not elaborate, the official document-the installation of ThinkPHP is very comprehensive, you can download the zip package through Composer, Git or directly to the ThinkPHP official website. The version I installed is 5.0.24.

Test run

After downloading and installing, if the download directory of the project is under the root directory of your local server, you can enter the address http://localhost/thinkphp5/public/ directly in the browser to enter the default welcome page of ThinkPHP5, as shown in the following figure, which indicates that ThinkPHP5 has been installed successfully.

In addition to running the address in the above way, we can also configure a virtual host to access the project through Apache or Nginx. If you are interested, you can view the specific tutorials online, and then configure the virtual host to access it.

Let's get to the point, let's analyze the implementation process of ThinkPHP5 step by step.

Entry file (publicindex.php)

After opening the public\ index.php file, we can see that the original code of the entry file is as follows

/ / [application entry file] / / define the application directory define ('APP_PATH', _ _ DIR__. '/.. / application/'); / / load the framework boot file require _ _ DIR__. '/.. / thinkphp/start.php'

The entry file code is very concise, just two lines of code, the function is

Define ('APP_PATH', _ DIR__. '/.. / application/'); define the constant APP_PATH of the application directory

Require _ _ DIR__. '/.. / thinkphp/start.php'; loads the framework boot file

In addition to the above two functions, we can also define our own constants in the entry file, such as adding a line of code define ('PUBLIC_PATH', _ DIR__.' /.. / public'), defining constants for the public directory and some preprocessing, etc.

Load the frame boot file (thinkphpstart.php)

Similarly, after entering the thinkphp\ start.php file, we can see that there is not much code.

Namespace think;// ThinkPHP boot file / / 1. Load the base file require _ DIR__. '/ base.php';// 2. Execute application App::run ()-> send ()

From these two short lines of code, we can see that there are mainly two left and right lines.

Require _ _ DIR__. '/ base.php'; loads the base file

App::run ()-> send (); execute the application

The following two big points will describe in detail what these two or so have done.

Load the base file (thinkphpbase.php)

We continued to open the thinkphp\ base.php file and found that it was finally no longer two lines of code like the first two files.

Define ('THINK_VERSION',' 5.0.24'); define ('THINK_START_TIME', microtime (true)); define (' THINK_START_MEM', memory_get_usage ()); define ('EXT',' .php'); define ('DS', DIRECTORY_SEPARATOR); defined (' THINK_PATH') or define ('THINK_PATH', _ DIR__. DS); define ('LIB_PATH', THINK_PATH. 'library'. DS); define ('CORE_PATH', LIB_PATH. 'think'. DS); define ('TRAIT_PATH', LIB_PATH. 'traits'. DS); defined ('APP_PATH') or define (' APP_PATH', dirname ($_ SERVER ['SCRIPT_FILENAME']). DS); defined ('ROOT_PATH') or define (' ROOT_PATH', dirname (realpath (APP_PATH)). DS); defined ('EXTEND_PATH') or define (' EXTEND_PATH', ROOT_PATH. 'extend'. DS); defined ('VENDOR_PATH') or define (' VENDOR_PATH', ROOT_PATH. 'vendor'. DS); defined ('RUNTIME_PATH') or define (' RUNTIME_PATH', ROOT_PATH. 'runtime'. DS); defined ('LOG_PATH') or define (' LOG_PATH', RUNTIME_PATH. 'log'. DS); defined ('CACHE_PATH') or define (' CACHE_PATH', RUNTIME_PATH. 'cache'. DS); defined ('TEMP_PATH') or define (' TEMP_PATH', RUNTIME_PATH. 'temp'. DS); defined ('CONF_PATH') or define (' CONF_PATH', APP_PATH); / / profile directory defined ('CONF_EXT') or define (' CONF_EXT', EXT); / / profile suffix defined ('ENV_PREFIX') or define (' ENV_PREFIX', 'PHP_'); / / configuration prefix of environment variable / / environment constant define (' IS_CLI', PHP_SAPI = = 'cli'? True: false); define ('IS_WIN', strpos (PHP_OS,' WIN')! = = false); / / load the Loader class require CORE_PATH. 'Loader.php';// loads the environment variable configuration file if (is_file (ROOT_PATH.). '.env') {$env = parse_ini_file (ROOT_PATH. '.env, true); foreach ($env as $key = > $val) {$name = ENV_PREFIX. Strtoupper ($key); if (is_array ($val)) {foreach ($val as $k = > $v) {$item = $name. '_'. Strtoupper ($k); putenv ("$item=$v");}} else {putenv ("$name=$val");} / / register automatic loading\ think\ Loader::register (); / / Registration error and exception handling mechanism\ think\ Error::register (); / / load convention configuration file\ think\ Config::set (include THINK_PATH. 'convention'. EXT)

Take a closer look and find that although the code has more than 60 lines, the function of the code is obvious, which mainly has the following six points.

Many system constants are defined using the define (',') function, plus two environment constants

Introduce the loader class (thinkphplibrarythinkloader.php) for subsequent use

Load the environment variable configuration file (the environment variable configuration file is named .env, which does not necessarily exist and is added as needed in the actual development process)

Call\ think\ Loader::register () to register the automatic loading mechanism

Registration system automatically loads

Composer autoload support

Register a namespace definition

Load the class library mapping file, which exists in classmap.php in the runtime cache directory

Automatically load the extend directory

Call\ think\ Error::register () to register the exception and error handling mechanism

Load convention profile (thinkphpconvention.php)

Execute the run method under thinkphplibrarythinkApp.php

For convenience, although the code of this run method is a little long, I still choose to post the whole method. Don't hit me.

/ * execute application * @ access public * @ param Request $request request object * @ return Response * @ throws Exception * / public static function run (Request $request = null) {$request = is_null ($request)? Request::instance (): $request; try {$config = self::initCommon (); / / Module / Controller binding if (defined ('BIND_MODULE')) {BIND_MODULE & & Route::bind (BIND_MODULE) } elseif ($config ['auto_bind_module']) {/ / entry automatically binds $name = pathinfo ($request- > baseFile (), PATHINFO_FILENAME); if ($name & &' index'! = $name & & is_dir (APP_PATH. $name) {Route::bind ($name);}} $request- > filter ($config ['default_filter']); / / default language Lang::range ($config [' default_lang']); / / enable multilingual mechanism to detect the current language $config ['lang_switch_on'] & & Lang::detect () $request- > langset (Lang::range ()); / / load the system language pack Lang::load ([THINK_PATH. 'lang'. DS. $request- > langset (). EXT, APP_PATH. 'lang'. DS. $request- > langset (). EXT,]); / / listen to app_dispatch Hook::listen ('app_dispatch', self::$dispatch); / / get application scheduling information $dispatch = self::$dispatch; / / URL route detection if (empty ($dispatch)) {$dispatch = self::routeCheck ($request, $config) if no scheduling information is set } / / record current scheduling information $request- > dispatch ($dispatch); / / record routing and request information if (self::$debug) {Log::record ('[ROUTE]'. Var_export ($dispatch, true), 'info'); Log::record (' [HEADER]'. Var_export ($request- > header (), true), 'info'); Log::record (' [PARAM]'. Var_export ($request- > param (), true), 'info');} / / listen app_begin Hook::listen (' app_begin', $dispatch); / / request cache check $request- > cache ($config ['request_cache'], $config [' request_cache_expire'], $config ['request_cache_except']) $data = self::exec ($dispatch, $config);} catch (HttpResponseException $exception) {$data = $exception- > getResponse ();} / clear the instantiated Loader::clearInstance of the class (); / / output data to the client if ($data instanceof Response) {$response = $data } elseif (! is_null ($data)) {/ / automatically identify the response output type $type = $request- > isAjax () by default? Config::get ('default_ajax_return'): Config::get (' default_return_type'); $response = Response::create ($data, $type);} else {$response = Response::create ();} / / listening app_end Hook::listen ('app_end', $response); return $response;}

This is about 90 lines of code, what exactly does it do? combined with annotation analysis, it mainly has the following functions

The first step: deal with the variable $request to ensure that it is valid and useful, not null

Step 2: self::initCommon () calls the initCommon () method in the current controller, initializes the application and returns configuration information

Load various configuration files

Load behavior extension file

Load public files

Load language Pack

Loader::addNamespace (self::$namespace, APP_PATH); registered namespace

Self::init () calls the init () method of this class to initialize the application.

Apply debug mode related processing

Load additional files and load related files through the value of the configuration item extra_file_list

Date_default_timezone_set ($config ['default_timezone']); set the system time zone

Call Hook::listen ('app_init'); listen for the behavior of the app_init tag

Step 3: determine whether to bind the module or controller

Step 4: system language setting and loading

Step 5: self::routeCheck ($request, $config) loads the routeCheck () method of the current controller for route detection

Check the route address configuration first, read the cache route first, and then import the route file configuration after it does not exist.

No routing configuration, direct parsing module / controller / operation

Returns module module information (module name, controller name, and operation method name)

Step 6: log routing and request information in debug mode

Step 7: self::exec ($dispatch, $config) calls the exec () method in the controller to perform call distribution

Distribute according to the type of user request, here is the type of module module

Call the self::module () execution module to deploy and initialize the module, get and set the current controller name and operation name

Step 8: clear the instantiation of the class and output the data in the corresponding format to the client, that is, the output interface seen by the user

This is the end of the article on "sample analysis of the loading process of TP5 framework from import to output interface". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it out for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report