Home > PHP Framework > ThinkPHP > ThinkPHP facade source code analysis

ThinkPHP facade source code analysis

咔咔
Release: 2020-11-06 14:31:10
Original
2191 people have browsed it

This article mainly describes the use and implementation process of the facade, and analyzes the source code.

Preface

Partners who use the framework should know that in 5.1, the framework added a new feature, which is the facade that this article will write, that is facade feature.

Anyone who has used this feature understands the benefit, that is, the method call can be directly called statically, without using the keyword static to define it.

Next, Kaka will take you to explore the story of facade from the following aspects.

1. Briefly understand the benefits of facade in the framework

I have written about configuration file loading before One article, at the end of that article mentioned several ways to obtain configuration information.

One of the methods is Config::get(). By this article, you should know that when using Config to obtain configuration information, you must first introduce use think\facade\Config, and then Because the alias is registered in the system, just use use Config.

Although we are using use think\facade\Config, the actual method called is __callStatic# in thinkphp/library/think/Facade.php ##method.

Then the

createFacade method of the same file will be executed.

Although I haven’t looked at the source code yet, it will be nice to know it. When calling the

createFacade method, it is obtained directly from the container class.

When learning containers, we all know that containers use the registration tree mode. When you need to use the corresponding object instance, you can directly obtain it, thus avoiding the repeated creation of a class. That's one of the advantages. Utilizing the characteristics of the container

For the previous use of config, you need to use the namespace of config and then instantiate it to call it.

If config is not allowed to be used at this time, you need to use the config class you created. If you do not use the facade mode, you need to modify a lot of code, and it is global.

But if you use the facade mode in the framework, you only need to rewrite the

getFacadeClass method. You only need to change the return result and define it yourself. Because they don't care what the instance calls when other files call it, they only care about the method name and return result.

2. The use of facade in the learning framework

First create a controller Facade and write the following content .

Here we simply use the facade method to obtain configuration file information.

ThinkPHP facade source code analysisHere you can see that use Config is used, which is the alias of the config class.

The alias setting is set in base.php.

ThinkPHP facade source code analysisHow to use facade correctly in the framework!

Create a new folder facade in the app directory to specifically store facade classes.

A Sessions class is created here.

ThinkPHP facade source code analysisFirst do a test to check whether there is any problem with the code. Test in the controller's facade file.

This is how it is handled when the facade is not used. You need to introduce the corresponding class, then instantiate it, and then use the instantiated class to make method calls.

ThinkPHP facade source code analysisPrint the result, the result is what we expected.

ThinkPHP facade source code analysisSo how do you change this code to facade mode! Follow Kaka's footsteps step by step.

First create two directories in the kaka directory, namely facade and util

ThinkPHP facade source code analysisWhy should we create these two folders! Everyone should know that util is a tool class, and this class file can be shared in other projects.

That is to say, we only need to implement one copy and then use it directly in other projects.

So you can copy the file directly to the util directory, just remember to modify the namespace.

ThinkPHP facade source code analysisThen create a new Sessions class in the facade directory and inherit Facade. Then write the content.

ThinkPHP facade source code analysisAt this point we are coming to the controller to test it.

You will find that the result is the same as before, but the obvious difference is that after using the facade mode, you can directly use the static method to call.

Do you still remember one of the benefits of facade mentioned before?

Assuming that this Sessions tool class will stop being used in the future, then we only need to modify the content in the getFacadeClass method.

ThinkPHP facade source code analysisThinkPHP facade source code analysis

##3. Optimize the use of facade in the framework# #In the above, we implemented the same function from instantiating the class to using the facade method.

Although the desired effect is displayed, the code is still not concise and beautiful enough, and the structure is relatively confusing.

Next, Kaka will provide you with a feasible plan. If you have other plans, you can put them forward! See you in the comments section.

In normal development work, it is impossible to have only one or a few customized facade classes. In complex projects, there will be many facade classes.

Since there are many, they need to be managed.

First create a configuration class belonging to the facade.

Map the proxy class with the actual class, and then set the alias.

ThinkPHP facade source code analysisAt this time, you need to create a hook file, and put the facade class registration and facade category name registration in it for execution.

ThinkPHP facade source code analysisThe last step is that the hook file is created but not executed.

So when should the hook file be executed? That is to load it when the application is initialized.

The application initialization configuration in TP5.1 is in the file application/tags.php.

Just configure the hook file in the application initialization configuration item.

ThinkPHP facade source code analysisTesting

The last step is to test, still execute the # in the application/index/controller/Facade.php file ##getUserInfoMethod.

According to the test results, we can know that there is no problem in writing the code of our solution.

ThinkPHP facade source code analysisHave you found a problem here, that is, since the alias of the facade class is defined in the hook, it is not used here. ThinkPHP facade source code analysis

Next we use aliases to test it.

ThinkPHP facade source code analysisThinkPHP facade source code analysis

4. Facade class source code analysis

Before parsing the source code Know two methods.

  • __callStatic: This method is called when a non-existing static method is accessed.
  • call_user_func_array: You can use this function to call the function directly.

We will start parsing from obtaining the configuration file

ThinkPHP facade source code analysisExecutionConfig::get('facade.');will be executed In the file thinkphp/library/think/facade/Config.php.

In this file, as mentioned before, if the getFacadeClass method exists, it will directly return the corresponding alias.

If it does not exist, you need to use the bind method to bind the facade.

If you don’t understand here, you need to go to the documentation and take a good look at the facade chapter!

ThinkPHP facade source code analysisThere is no get method in the above class, so the __callStatic method in the thinkphp/library/think/Facade.php file will be called directly.

This method is directly explained at the beginning of the article. This method will be called when accessing a non-existent static method.

ThinkPHP facade source code analysisThen the createFacademethod in this class will be executed

There is a line of code in this method that looks like this$facadeClass = static ::getFacadeClass();This code will be explained in detail below.

Because there are the same methods in subclasses and the same methods in this class, but the methods in this class do not have any return value.

At this time, are you confused at all? Which method will be executed by the static used here? Or think about it this way, why the subclass method is executed.

Keep these questions and I will explain them to you in detail below. Let’s read the source code of the facade class first.

In this method, we mainly look at the several places I circled.

The first place is to get the alias of the class from the getFacadeClass method of the subclass.

The second point is that when the subclass does not have a getFacadeClass method, it is obtained from the manually bound properties.

The third place is the container mentioned in the previous article. I won’t explain it in detail here. If you don’t know how, click on the homepage to read the previous article.

ThinkPHP facade source code analysis
createFacade method

5. static keyword

in I have to explain the static keyword here.

New learning partners may only know that static is used to define static variables and static methods.

Of course, I won’t tell you how to define static methods and static variables here, but I will talk about a very, very small detail.

Let’s look at an example first. This example was also adapted by Kaka based on the facade source code when reading the facade source code.

Kaka has created two new files here, namely test and test1.

test inherits the test1 file and has the same method getKaka.

ThinkPHP facade source code analysis
Create two new files

test source code

ThinkPHP facade source code analysis
test source code

test1 source code

ThinkPHP facade source code analysisController calls

ThinkPHP facade source code analysisPrint resultsThinkPHP facade source code analysisAre you a little confused at this time? Why is 147 printed here instead of 456!

Modify the code of test1 and change static to self

ThinkPHP facade source code analysisPrint the results

ThinkPHP facade source code analysisI believe everyone can read the code using self I understand, so why do I get results that may not be clear when using static!

At this point, the document starts to take effect, but when you open the PHP document, you will find that there is no explanation of this situation in the static article.

After many tests and information review by Kaka, the final summary results are as follows.

static::$test If it is inherited, it will call the subclass by default, otherwise it will call itself

self::$test If it is inherited, it will call this class by default

To illustrate in this example, when test inherits test1.

When using static to call method getKaka in test1, the default call is getKaka in the test class, which is the method of the subclass.

When using self to call the method getKaka in test1, the default call is getKaka in the test1 class, which is the method of this class.

This small detail was also discovered by Kaka accidentally. If there is anything wrong, you can point it out and Kaka will make changes.

Because there is another situation in inheritance, Kaka will test it privately, so I won’t explain it here.

The explanation of this static here is mainly to explain this line of code in the thinkphp/library/think/Facade.php file.

Because the method called by this line of code exists in both the subclass and the parent class, Kaka wrote it to give a brief introduction in order to avoid confusing everyone.

ThinkPHP facade source code analysis
thinkphp/library/think/Facade.php

##6. Summary

First let’s take a look at the facade flow chart to see more clearly the specific execution process of the facade class.

The source code of the facade class is very simple. Except for a few uncommon knowledge points, I believe the code can be understood clearly. ThinkPHP facade source code analysis

This is mainly to make a short summary after reading the facade class.

The facade class is mainly a function implemented in combination with the container, because the container is needed to return the corresponding instance. The article about the container has also been completed. If you have any questions about the container, you can go to the beginning of the article. Just read the corresponding article.

This article introduces how to use the facade in the container, and provides you with the best way to use it. The best here is Kaka’s personal opinion, because in this way Kaka uses nearly two years.

It is very practical in terms of code robustness and scalability.

Then about the static keyword, I would like to add some unpopular knowledge to everyone. When a class inherits a class, when the parent class uses the static keyword, the method of the subclass is called by default.

The summary here is only for the examples in this article.

In fact, Kaka wants to explain one point to you here, which is return call_user_func_array([static::createFacade(), $method], $params);

Because in the previous usage, the parameters were directly methods, but here we encounter the array form, so what do the two values ​​​​in this array represent?

The first value is the instance, and the second value is the method in the instance.

Aboutcall_user_func_arrayThe use of this method will not be done by KaKa. You only need to know that it will execute the incoming method.

The source code analysis of the facade ends here. The most important thing is to understand the container, because the facade is implemented on the basis of the container. This is why Kaka writes the container first and then writes the facade.

In addition, Kaka also gave a plan for using the facade. If you have a better plan, you can give a general idea 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 facade source code analysis. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template