Home >PHP Framework >ThinkPHP >ThinkPHP automatically loads Loader source code analysis

ThinkPHP automatically loads Loader source code analysis

咔咔
咔咔Original
2020-09-16 10:22:172516browse

After thinking about it for a long time, I finally started writing a series of articles. I hope to write a series of articles that can handle promotions and interviews. When you read this article, if you find hot interview questions or technical difficulties that Kaka has not written, please point them out in the comment area and improve them together.

Foreword

We are currently sorting out the PHP advanced roadmap. If you have any good suggestions, Kaka will include them as soon as possible.

1. Automatic loading loader source code analysis

##1-1 Learning Objectives

  • Automatic loading of classes
  • Two ways of automatic loading of classes
  • spl_autoload_register must use
  • to implement automatic loading of custom file classes

1-2 Composer loads

ThinkPHP automatically loads Loader source code analysis
Insert image description here
Click from the picture above In the analysis diagram given by Ka, the loader class is first loaded in base.php, and then the register method is called.

ThinkPHP automatically loads Loader source code analysisCome tothinkphp\library\think\Loader.phpThere is a register method. In this method, we first learn the first knowledge pointspl_autoload_register()Talk about the past and present life and simple use of spl_autoload_register, click directly to view.

The next step is the root path of the project and the path of composer.

ThinkPHP automatically loads Loader source code analysis
Insert image description here

From here on, the composer file is loaded, and the process is very simple

  • 1. Determine whether composer is a directory
  • 2. Determine whether autoload_static.php under the path is a file
  • 3. Introduce the autoload_static.php file
  • 4. Return all declared classes array return
  • 5. Get the last class ComposerStaticInit30742487e00917c888d89ba216f165b9
  • 6. Determine whether the data in the array exists in ComposerStaticInit30742487e00917c888d89ba216f165b9

##Then you can go to the vendor\composer\autoload_static.php file. See these two attributesThinkPHP automatically loads Loader source code analysis

ThinkPHP automatically loads Loader source code analysisHere is a piece of code that some students will probably go around hereself::${$attr} = $composerClass::${$attr};, here is $attr is'prefixLengthsPsr4', 'prefixDirsPsr4', 'fallbackDirsPsr4', 'prefixesPsr0', 'fallbackDirsPsr0', 'classMap', 'files'For these data, add a to the outer layer $ symbol.

Thus, the corresponding attribute values ​​​​are directly obtained in the ComposerStaticInit30742487e00917c888d89ba216f165b9 class, which is the two attribute values ​​in the picture above.

ThinkPHP automatically loads Loader source code analysis
Insert image description here

1-3 Register namespace The

file is still the register method of thinkphp\library\think\Loader.php

where two command spaces are registered. They are think and traits respectively. Then you will enter the addNamespace methodThinkPHP automatically loads Loader source code analysisIn the addNamespace method, the Psr4 space

is added

ThinkPHP automatically loads Loader source code analysisThen we come to the addPsr4 method, which will register both namespaces into the $prefixLengthsPsr4 and $prefixDirsPsr4 properties of the ComposerStaticInit1e269472f484e157e90227b420ffca7a class

ThinkPHP automatically loads Loader source code analysisIn order to verify the above, make a breakpoint debugging. It should be clear when you see these data. As for traits, the same registration method is used.

As of now, the namespace has been registered. Next, let’s study what the psr4 namespace is. ThinkPHP automatically loads Loader source code analysis

1-4 What is Psr4

psr is simply understood to be the file path, automatic Load the relevant specifications of the corresponding class. Currently TP5.1 uses the psr4 specification

The class here refers to the class, interface, and super class structure

A complete class requires the following structure\<namespace>(\<subnamespace>)*\<class name></class></subnamespace></namespace>

The following specifications come from PHP documentation

  • The complete class name must have a top-level namespace, called "vendor namespace";

  • The complete class name can have one or more sub-namespaces;

  • The complete class name must have a final class name;

  • The underscore in any part of the complete class name has no special meaning;

  • Complete class Names can be composed of any uppercase or lowercase letters;

  • All class names must be case-sensitive.

The following is an official example. If you can understand this psr specification, try to understand itThinkPHP automatically loads Loader source code analysis

1-5 Loading the class library mapping file

#At this point, there will definitely be a question, why is there no classmap.php here? this file. ThinkPHP automatically loads Loader source code analysisDon’t rush, don’t panic, first executephp think optimize:autoloadGet the file outThinkPHP automatically loads Loader source code analysisYou will eventually reach the addClassMap method. In this method, just classmap.phpThe data of this file is assigned to $classMap, there is no other usageThinkPHP automatically loads Loader source code analysis

##1-6 Automatically load the extend directory

extend This directory is used by everyone who has used the TP framework. Customized class library files can be stored in this directory.

As you can see from the picture below, it is loaded using the addAutoLoadDir method.

ThinkPHP automatically loads Loader source code analysisIn the method, the extend path is only assigned to $fallbackDirsPsr4. This attribute.

ThinkPHP automatically loads Loader source code analysisUp to hereLoader::register();This part is over, then we will take an in-depth look at the internal implementation and practical cases.

There are four attributes in the above reading source code, let’s briefly organize them

ThinkPHP automatically loads Loader source code analysis
Insert picture description here

2. Briefly explain the loading process of the class

ThinkPHP automatically loads Loader source code analysis
Insert picture description here

There is a function when I just started parsing the source code herespl_autoload_register

When the class to be used has not been introduced, this function will be triggered before PHP reports an error, and the undefined class name will be passed in as a parameter and will be executed directlythink\\Loader::autoloadThis method

ThinkPHP automatically loads Loader source code analysisThe first unloaded class after the breakpoint is think\Error

ThinkPHP automatically loads Loader source code analysisWhy is think\Error! You can go back to thinkphp/base.php and take a look. When the automatic loading is completed, the first class to be executed is Error

ThinkPHP automatically loads Loader source code analysis. You can simply do a test. This Error is changed to Kaka, print it, and the class is changed to Kaka. At this point everyone has a certain understanding of the automatic loading mechanism of this class.

When the class used has not been introduced, this class will be passed as a parameter to the autoload method of thinkphp/library/think/Loader.php.

ThinkPHP automatically loads Loader source code analysisCome here and take a look at the autoload method

ThinkPHP automatically loads Loader source code analysisStart with the findFile method, and pass the unnamed class into this method. In the findFile method The file mapped by the think\Error class will be returned directly from the classMap attribute

ThinkPHP automatically loads Loader source code analysisAfter returning the full path of the think\Error class to the file variable of autoload, the case of the win environment is judged once.

Then directly use include to introduce the file until it returns.

Up to here is a complete automatic loading and analysis of the class.

ThinkPHP automatically loads Loader source code analysisAlthough it ends here, I still have to mention one thing: the attribute $classMap, this attribute is based on the file classmap.php, The generation of this file also requires executing the command php think optimize:autoload.

How does the program execute when this file is not generated!

All the previous processes are the same, only findFile is different here, let’s briefly sort it out.

At this time the code will definitely not go to classMap

ThinkPHP automatically loads Loader source code analysisFirst obtain the think\Error file

ThinkPHP automatically loads Loader source code analysisThen obtain the namespace through the two attributes in Composer's automatic loading, and then splice the think\Error.php file

ThinkPHP automatically loads Loader source code analysisThe final result returned is also the file D:\phpstudy_pro\WWW\ThinkPHPSourceCodeAnalysis\thinkphp\library\think\Error.php.

The code here needs to be read carefully.

The automatic loading of classes is completely over here.

3. How to implement automatic loading of classes with custom files

First create a folder kaka

ThinkPHP automatically loads Loader source code analysisAt this time, introduce the file Kaka.php in the controller index

ThinkPHP automatically loads Loader source code analysis for direct access. At this time, this class will definitely report an error, so what should we do to access it directly? Woolen cloth!

ThinkPHP automatically loads Loader source code analysis
Insert image description here

At this time, the importance of the source code is revealed. Remember to load the register automatically. In the function, the extend directory is loaded

ThinkPHP automatically loads Loader source code analysis
Insert image description here

At this time, add a kaka directory , visit it directly

ThinkPHP automatically loads Loader source code analysisNo problem, it comes out directly. Everything is OKThinkPHP automatically loads Loader source code analysisHere we will talk about the loading method of extent

When I talked about registering the automatic loading class library directory, I just explained that I just saved the path to the $fallbackDirsPsr4 attribute, there is no To elaborate, the next step is to explain these.

The only way to read the source code is to implement it and then check it

ThinkPHP automatically loads Loader source code analysis
Insert picture description here

As long as the defined class is entered, it will go to autoload for automatic loading

The same will happen Enter the findFile method

ThinkPHP automatically loads Loader source code analysisYou can see this code in the findFile method. Are you familiar with this attribute? It is added to when the extend directory is automatically loaded. $fallbackDirsPsr4 attribute.

ThinkPHP automatically loads Loader source code analysisLook at the data when printing the parameter class in findFile

You can clearly seetest\KakaThis class

ThinkPHP automatically loads Loader source code analysisThinkPHP automatically loads Loader source code analysisAt this time, print the file returned in the $fallbackDirsPsr4 attribute

ThinkPHP automatically loads Loader source code analysisThen use __include_file to include it directly D:\phpstudy_pro\WWW\ThinkPHPSourceCodeAnalysis\kaka\test\Kaka.phpThe file we defined.

How does the above custom file realize automatic loading of classes, and that is the loading method of extend

4. Summary

All the processes regarding automatic class loading are complete. If there are any errors, please leave them in the comment area!

Persistence in learning, persistence in blogging, and persistence in sharing are the beliefs that Kaka has always upheld since his career. I hope that Kaka’s articles in the huge Internet can bring you a little Silk help. My name is Kaka, see you next time.

The above is the detailed content of ThinkPHP automatically loads Loader source code analysis. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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