当前位置:网站首页>Analysis of the source code of ThinkPHP facade

Analysis of the source code of ThinkPHP facade

2020-11-09 10:50:00 Click-

This paper mainly describes the use and implementation process of facade and the in-depth analysis of source code .

@

    Preface

    All partners who use the framework should know that in 5.1 A new feature of the framework is the facade of this article , That is to say facade This feature .

    Anyone who has used this feature knows the benefits , That is, method calls can be called directly and statically , No more keywords static To define .

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

    One 、 Briefly understand the benefits of facade in the framework

    I have written a article about loading configuration file before , How to get the information mentioned in the last article .

    One of the ways is Config::get(), You should know how to use Config When getting configuration information , You have to introduce use think\facade\Config, Because of the alias registered in the system , So use it directly use Config that will do .

    Although we use use think\facade\Config, But the method actually called is thinkphp/library/think/Facade.php Medium __callStatic Method .

    Then the same file will be executed createFacade Method .

    Although we haven't looked at the source code yet , Just look and know , Calling createFacade Method is directly obtained from the container class .

    When learning about containers, we all know that containers use the registration tree pattern , When you need to use the corresponding object instance, you can get it directly , This avoids the repeated creation of a class . That's one of the advantages . Take advantage of the characteristics of the container

    For previous use config Come on , Need to use config The namespace of , Then it can be called by instantiation .

    If at this time config No more use of , You need to use your own created config class , If you don't use facade mode , You need to modify a lot of code , And it's global .

    But if you use the framework facade After the facade mode , You just need to rewrite getFacadeClass This method can , You just need to change the return result in it and define it by yourself , Because where other files are called, they don't care what the instance calls , Only care about method name and return result .

    Two 、 In the framework of learning facade Use

    First create a controller Facade, And write the following .

    This is just a simple way to use the facade to get the configuration file information .

     Insert picture description here You can see here that use Config, This is config Alias of class .

    The alias is set in base.php Set in the .

     Insert picture description here How to use it correctly in the framework facade Well !

    stay app Create a new folder in the directory facade, It is used to store the facade class .

    We created one here Sessions Class .

     Insert picture description here Do a test first , Check whether the code is written incorrectly . In the controller facade Test in file .

    This is what happens when you don't use a facade , We need to introduce the corresponding class , Then you instantiate it , Method calls are made with instantiated classes .

     Insert picture description here Print the results , The result is what we expect .

     Insert picture description here So how does this code change to facade mode ! Step by step, follow the footsteps of Kaka .

    First in kaka Create two directories under the directory , Respectively facade and util

     Insert picture description here Why create these two folders !util We should all know that is tool class , This kind of file can be shared in other projects .

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

    So you can directly copy the file to util Under the table of contents , Remember to change the namespace .

     Insert picture description here And then to facade Create a new one in the directory Sessions Class , And inheritance Facade. And then write it down .

     Insert picture description here At this time, we are going to test the controller .

    You'll find that the results are the same as before , But one obvious difference is the use of facade After the model , It can be called directly in a static way .

    Remember talking about one of the benefits of appearance before ?

    Suppose this Sessions The utility class will be discontinued one day , So we just need to modify getFacadeClass The content in the method can be .

     Insert picture description here  The results of the facade printing

    3、 ... and 、 Optimization in the framework facade Use

    In the previous section, we implemented the same function from instantiating classes to using facade methods .

    Although the desired effect is shown , But the code is still not concise and elegant , The structure is also chaotic .

    Next, Kaka will provide you with a feasible plan , If you have any other plans you can come up with ! See the comments section .

    In the normal development work, the custom facade class cannot have only one or several , In complex projects, there are many facade classes .

    Since there are many , That requires management .

     Facade files First, create a configuration class that belongs to the facade .

    And match the proxy class to the actual class , Then set the alias .

     Facade class configuration file You need to create a hook file , Put the facade class registration and facade class alias registration in it for execution .

     Hook file And the last step , The hook file is created but not executed .

    When should hook files be executed ! That is to load when the application is initialized .

    stay TP5.1 The configuration of application initialization in is in application/tags.php In this file .

    Configure the hook file in the configuration item of application initialization .

     Application initial configuration test

    The last step is to test , It's still execution application/index/controller/Facade.php In the document getUserInfo Method .

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

     Execute test method file  test result Did you find a problem here , Since the alias of the facade class is defined in the hook , But it's not used here .

    Let's test it with aliases .

     Facade alias test  test result

    Four 、 Facade class source code analysis

    Before parsing the source code, know two methods .

    • __callStatic: When accessing a static method that does not exist , This method is called .
    • call_user_func_array: You can use this function to call the function directly .

    We start by getting the configuration file

     Get configuration information perform Config::get('facade.'); Will execute to the file thinkphp/library/think/facade/Config.php in .

    In this document, that's what I said before , If there is getFacadeClass Method will directly return the corresponding alias .

    If it doesn't exist, you need to use bind Method to do facade binding .

    If you don't understand here, you need to go to the document and have a good look at the chapter of facade !

    thinkphp/library/think/facade/Config.php It doesn't exist in the upper class get Methodical , So it calls thinkphp/library/think/Facade.php In the document __callStatic Method .

    This method is explained directly at the beginning of the article , This method is called when accessing a static method that does not exist .

    __callStatic Method Then it will execute the... In this class createFacade This method

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

    Because there are the same methods in subclasses , There is the same method in this class, but the method in this class has no return value .

    Do you have any confusion at this time , the static Where exactly will it be implemented . Or think about it this way , Why does a subclass of a method execute .

    Keep these questions, which will be discussed in detail below , First, read the source code of the facade class .

    In this method, I mainly look at several places I circle .

    The first is from subclasses getFacadeClass Method to get the alias of the class .

    The second is when subclasses don't have getFacadeClass When the method is used , Get from manually bound properties .

    The third is the container mentioned in the previous article , I don't elaborate here , If not, click on the home page to see the previous article .

    createFacade Method
    createFacade Method

    5、 ... and 、static keyword

    It has to be explained here that static This keyword .

    The new learning partner can only know 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 , It's about a very, very small detail .

    Let's take a look at an example , This example is also in reading the facade source code , Kaka according to the facade source code adapted from .

    There are two new files here , Respectively test and test1.

    test Inherit test1 file , And they all have the same way getKaka.

     Create two new files
    Create two new files

    test Source code

    test Source code
    test Source code

    test1 Source code

    test1 Source code The controller calls

     Insert picture description here Print the results  Print the results Do you have any doubts at this time , How to print it out here is 147, instead of 456 Well !

    modify test1 Code for , hold static Change it to self

    test1 Modify the code Print the results

     Insert picture description here Use self I believe you can understand the code , Then why use static There may be results that may not be clear !

    This is where the documentation comes into play , But when you turn on PHP The document will find , stay static There is no explanation for this kind of situation in this article .

    After many times of testing and consulting information , The final conclusion is as follows .

    static::$test If any of them are inherited Default call subclass , Otherwise, it calls itself

    self::$test If any of them are inherited , This class is called by default

    In this example, it is shown that , When test Inherit test1 when .

    stay test1 Use in static Calling method getKaka when , The default call is test Class getKaka, That is, the method of subclass .

    stay test1 Use in self Calling method getKaka when , The default call is test1 Class getKaka, This is the method of this kind .

    This little detail is also found by accident , If there is anything wrong with it, you can bring it up , Click to make changes .

    Because there is another case of inheritance , Kaka will test in private , It doesn't mean .

    Here's to this static The main purpose of explanation is to explain thinkphp/library/think/Facade.php This line of code in the file .

    Because the method called by this line of code exists in both the child class and the parent class , So Kaka, in order not to let everyone appear confused, wrote out a simple introduction .

    thinkphp/library/think/Facade.php
    thinkphp/library/think/Facade.php

    6、 ... and 、 summary

    Let's start with a facade flow chart , You can see the specific execution process of facade class more clearly .

     Facade execution flow chart The source code of facade class is very simple , Except for a few less common knowledge points , I believe you can see the code clearly .

    Here is mainly after reading the facade class , Make a short summary .

    Facade class is a function realized by combining container , Because the container is needed to return the corresponding instance , The article on containers has also been completed , If there is no container, you can read the corresponding article at the beginning of the article .

    This article introduces how to use facade in container , And to provide you with the best way to use , The best thing here is a personal opinion , Because it's been used for nearly two years .

    Whether from the robustness or extensibility of the code is very practical .

    And then it's about static keyword , I have to add a little bit of cold knowledge to you , When a class inherits a class , In the parent class static When a keyword , Method of subclass called by default .

    The summary here is only for the example of this article .

    In fact, we still want to explain one point here, that is return call_user_func_array([static::createFacade(), $method], $params);

    Because in the previous usage, the elder brother parameter is the method directly , But here we come across array form , So what do the two values in this array represent !

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

    About call_user_func_array The use of this method will not do a case to show you , Just know that it will execute the incoming method .

    Here on the facade of the source code analysis is over , The most important thing is to understand the container , Because facade is realized on the basis of container , This is the reason why the container is written first and the facade is written .

    There is also about the use of the facade, Kaka also gives the scheme , If you have a better plan, you can give a general idea in the comments section .

    Keep learning 、 Keep blogging 、 To insist on sharing is the belief that khaka has been holding since he was employed . I hope the articles in the Internet can bring you a little help . I'm Kaka , See you next time .

    版权声明
    本文为[Click-]所创,转载请带上原文链接,感谢