Home PHP Framework ThinkPHP Analyze ThinkPHP5 loading process

Analyze ThinkPHP5 loading process

Jun 11, 2020 am 09:34 AM
php thinkphp

Analyze ThinkPHP5 loading process

Installing ThinkPHP

How to install it, I won’t go into details. The official document-Installing ThinkPHP talks a lot Complete, you can download the zip package through Composer, Git or go directly to the ThinkPHP official website. The version I installed is 5.0.24

Test run

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

Analyze ThinkPHP5 loading process

In addition to the above method of address operation, we can also configure a virtual host through Apache or Nginx to access the project. Those who are interested can view it online Specific tutorial, and then configure the virtual host for access.

Let’s get to the point, let’s analyze the execution process of ThinkPHP5 step by step...

Entry file (public\index.php)

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

1

2

3

4

5

// [ 应用入口文件 ]

// 定义应用目录

define('APP_PATH', __DIR__ . '/../application/');

// 加载框架引导文件

require __DIR__ . '/../thinkphp/start.php';

Copy after login

The entry file code is very simple, just two lines of code, with the functions

1

2

define('APP_PATH', __DIR__ . '/../application/');定义应用目录的常量APP_PATH

require __DIR__ . '/../thinkphp/start.php';加载框架引导文件

Copy after login

In addition to the two above In addition to the function, we can also define our own constants in the entry file, such as adding a line of code define('PUBLIC_PATH', __DIR__ .'/../public'); to define the constants of the public directory and some preprocessing.

Load the framework boot file (thinkphp\start.php)

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

1

2

3

4

5

6

namespace think;

// ThinkPHP 引导文件

// 1. 加载基础文件

require __DIR__ . '/base.php';

// 2. 执行应用

App::run()->send();

Copy after login

From this short two lines of code, we can see that there are two main left and right sides

1

2

require __DIR__ . '/base.php';加载基础文件

App::run()->send();执行应用

Copy after login

The following two major points will introduce in detail what these two left and right sides do

Load the base file (thinkphp\base.php)

We continue to open the thinkphp\base.php file and find that this file is no longer like the first two files, with only two Line of code...

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

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); // 配置文件目录

defined('CONF_EXT') or define('CONF_EXT', EXT); // 配置文件后缀

defined('ENV_PREFIX') or define('ENV_PREFIX', 'PHP_'); // 环境变量的配置前缀

// 环境常量

define('IS_CLI', PHP_SAPI == 'cli' ? true : false);

define('IS_WIN', strpos(PHP_OS, 'WIN') !== false);

// 载入Loader类

require CORE_PATH . 'Loader.php';

// 加载环境变量配置文件

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");

        }

    }

}

// 注册自动加载

\think\Loader::register();

// 注册错误和异常处理机制

\think\Error::register();

// 加载惯例配置文件

\think\Config::set(include THINK_PATH . 'convention' . EXT);

Copy after login

Looking carefully, I found that although the code has more than 60 lines, the function of the code is obvious. The main functions are the following six points

  1. Usedefine('', '')The function defines many system constants, plus two environment constants
  2. Introduce the loader class (thinkphp\library\think\loader.php) for subsequent use
  3. Load the environment variable configuration file (the name of the environment variable configuration file is .env. This file does not necessarily exist. It is added as needed during the actual development process)
  4. Calling\think\Loader::register()Register automatic loading mechanism
    • Register system automatic loading
    • ComposerAutomatic loading support
    • Register namespace definition
    • Load the class library mapping file, which exists in the runtimecache directoryclassmap.php
    • Automatic loadingextendDirectory
  5. Call \think\Error::register()Register exception and error handling mechanism
  6. Load custom configuration File (thinkphp\convention.php)

Execute the run method under the application (thinkphp\library\think\App.php)

For convenience, this Although the code of the run method is a bit long, I still choose to post the entire method. Don’t hit me.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

/**

 * 执行应用程序

 * @access public

 * @param  Request $request 请求对象

 * @return Response

 * @throws Exception

 */

public static function run(Request $request = null)

{

    $request = is_null($request) ? Request::instance() : $request;

    try {

        $config = self::initCommon();

        // 模块/控制器绑定

        if (defined('BIND_MODULE')) {

            BIND_MODULE && Route::bind(BIND_MODULE);

        } elseif ($config['auto_bind_module']) {

            // 入口自动绑定

            $name = pathinfo($request->baseFile(), PATHINFO_FILENAME);

            if ($name && 'index' != $name && is_dir(APP_PATH . $name)) {

                Route::bind($name);

            }

        }

        $request->filter($config['default_filter']);

        // 默认语言

        Lang::range($config['default_lang']);

        // 开启多语言机制 检测当前语言

        $config['lang_switch_on'] && Lang::detect();

        $request->langset(Lang::range());

        // 加载系统语言包

        Lang::load([

            THINK_PATH . 'lang' . DS . $request->langset() . EXT,

            APP_PATH . 'lang' . DS . $request->langset() . EXT,

        ]);

        // 监听 app_dispatch

        Hook::listen('app_dispatch', self::$dispatch);

        // 获取应用调度信息

        $dispatch = self::$dispatch;

        // 未设置调度信息则进行 URL 路由检测

        if (empty($dispatch)) {

            $dispatch = self::routeCheck($request, $config);

        }

        // 记录当前调度信息

        $request->dispatch($dispatch);

        // 记录路由和请求信息

        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');

        }

        // 监听 app_begin

        Hook::listen('app_begin', $dispatch);

        // 请求缓存检查

        $request->cache(

            $config['request_cache'],

            $config['request_cache_expire'],

            $config['request_cache_except']

        );

        $data = self::exec($dispatch, $config);

    } catch (HttpResponseException $exception) {

        $data = $exception->getResponse();

    }

    // 清空类的实例化

    Loader::clearInstance();

    // 输出数据到客户端

    if ($data instanceof Response) {

        $response = $data;

    } elseif (!is_null($data)) {

        // 默认自动识别响应输出类型

        $type = $request->isAjax() ?

        Config::get('default_ajax_return') :

        Config::get('default_return_type');

        $response = Response::create($data, $type);

    } else {

        $response = Response::create();

    }

    // 监听 app_end

    Hook::listen('app_end', $response);

    return $response;

}

Copy after login

What exactly does this about 90 lines of code do? Based on the analysis of comments, the main ones are as follows: Step function

  • The first step: Process the variable $request, ensure that it is valid and not null
  • The second step: self::initCommon() Call The initCommon() method in the current controller is responsible for initializing the application and returning configuration information
    • Loader::addNamespace(self::$namespace, APP_PATH);Register namespace
    • self::init()Call the init() method of this class to initialize the application
      • Load various configuration files
      • Load behavior extension files
      • Load public files
      • Load language pack
    • Apply debug mode related processing
    • Load additional files through configuration itemsextra_file_listValue to load related files
    • date_default_timezone_set($config['default_timezone']);Set the system time zone
    • Call Hook::listen('app_init ');The behavior of monitoring the app_init tag
  • Step 3: Determine whether to bind the module or controller
  • Step 4: System language setting and loading
  • The fifth step:self::routeCheck($request, $config)Load the routeCheck() method of the current controller for route detection
    • Route first Address configuration detection, first read the cache route, if it does not exist, then import the routing file configuration
    • No routing configuration, directly parse the module/controller/operation
    • Return module module information (module name, control Device name and operation method name)
  • Step 6: Enable debugging mode and record routing and request information logs
  • Step 7:self:: exec($dispatch, $config)Call the exec() method in the controller to execute the call distribution
    • Perform distribution processing according to the user request type, here is the module module type
    • Callself::module()Execute the module, perform module deployment and initialization, obtain and set the current controller name and operation name
  • Step 8: Clear the instantiation of the class , and output data in the corresponding format to the client, that is, the output interface seen by the user

Recommended tutorials: "PHP" "ThinkPHP Tutorial"

The above is the detailed content of Analyze ThinkPHP5 loading process. 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 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

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

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 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.

What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? Apr 07, 2025 am 12:02 AM

In PHP, you can effectively prevent CSRF attacks by using unpredictable tokens. Specific methods include: 1. Generate and embed CSRF tokens in the form; 2. Verify the validity of the token when processing the request.

See all articles