Home PHP Framework ThinkPHP ThinkPHP facade source code analysis

ThinkPHP facade source code analysis

Nov 05, 2020 pm 12:02 PM
thinkphp

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!

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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)

How to run thinkphp project How to run thinkphp project Apr 09, 2024 pm 05:33 PM

To run the ThinkPHP project, you need to: install Composer; use Composer to create the project; enter the project directory and execute php bin/console serve; visit http://localhost:8000 to view the welcome page.

There are several versions of thinkphp There are several versions of thinkphp Apr 09, 2024 pm 06:09 PM

ThinkPHP has multiple versions designed for different PHP versions. Major versions include 3.2, 5.0, 5.1, and 6.0, while minor versions are used to fix bugs and provide new features. The latest stable version is ThinkPHP 6.0.16. When choosing a version, consider the PHP version, feature requirements, and community support. It is recommended to use the latest stable version for best performance and support.

How to run thinkphp How to run thinkphp Apr 09, 2024 pm 05:39 PM

Steps to run ThinkPHP Framework locally: Download and unzip ThinkPHP Framework to a local directory. Create a virtual host (optional) pointing to the ThinkPHP root directory. Configure database connection parameters. Start the web server. Initialize the ThinkPHP application. Access the ThinkPHP application URL and run it.

Which one is better, laravel or thinkphp? Which one is better, laravel or thinkphp? Apr 09, 2024 pm 03:18 PM

Performance comparison of Laravel and ThinkPHP frameworks: ThinkPHP generally performs better than Laravel, focusing on optimization and caching. Laravel performs well, but for complex applications, ThinkPHP may be a better fit.

Development suggestions: How to use the ThinkPHP framework to implement asynchronous tasks Development suggestions: How to use the ThinkPHP framework to implement asynchronous tasks Nov 22, 2023 pm 12:01 PM

"Development Suggestions: How to Use the ThinkPHP Framework to Implement Asynchronous Tasks" With the rapid development of Internet technology, Web applications have increasingly higher requirements for handling a large number of concurrent requests and complex business logic. In order to improve system performance and user experience, developers often consider using asynchronous tasks to perform some time-consuming operations, such as sending emails, processing file uploads, generating reports, etc. In the field of PHP, the ThinkPHP framework, as a popular development framework, provides some convenient ways to implement asynchronous tasks.

How to install thinkphp How to install thinkphp Apr 09, 2024 pm 05:42 PM

ThinkPHP installation steps: Prepare PHP, Composer, and MySQL environments. Create projects using Composer. Install the ThinkPHP framework and dependencies. Configure database connection. Generate application code. Launch the application and visit http://localhost:8000.

How is the performance of thinkphp? How is the performance of thinkphp? Apr 09, 2024 pm 05:24 PM

ThinkPHP is a high-performance PHP framework with advantages such as caching mechanism, code optimization, parallel processing and database optimization. Official performance tests show that it can handle more than 10,000 requests per second and is widely used in large-scale websites and enterprise systems such as JD.com and Ctrip in actual applications.

RPC service based on ThinkPHP6 and Swoole to implement file transfer function RPC service based on ThinkPHP6 and Swoole to implement file transfer function Oct 12, 2023 pm 12:06 PM

RPC service based on ThinkPHP6 and Swoole implements file transfer function Introduction: With the development of the Internet, file transfer has become more and more important in our daily work. In order to improve the efficiency and security of file transfer, this article will introduce the specific implementation method of the RPC service based on ThinkPHP6 and Swoole to implement the file transfer function. We will use ThinkPHP6 as the web framework and utilize Swoole's RPC function to achieve cross-server file transfer. 1. Environmental standard

See all articles