This article mainly focuses on the implementation of the internal containers and facades of the framework as a benchmark,
I have analyzed the source code analysis of automatic loading of classes and configuration file loading before. This article is the third article, which mainly analyzes the source code for the implementation of containers and facade classes. And learn some knowledge points to implement this function.
is learning There are two design patterns that you need to understand before containers and facades, singleton mode and registration tree mode.
First give a brief explanation of the singleton mode.
This is a simple singleton mode implemented by Kaka. Check the above three features to see if they are consistent.
The static variable is instance
It has a structure and is private
The last one is the static method getInstance
Let’s do a simple test
Still testing in the index controller. In order to confirm that its class has only been instantiated once, it has been called four times.
Visit this method to take a look
new-class is executed only once, which directly proves that the created class is only instantiated once. A question I had before Kaka here is why the constructor here uses private attributes.
Have you ever had this question before? Kaka will take you to answer it
The constructor method of defining private properties in this class is to prevent its class from being instantiated externally.
When this class is instantiated externally, the error shown below will be reported.
So why do I mention the singleton model here! This is because
will be used in the source code of the next learning container. For example, in the thinkphp/library/think/Container.php
class below, there is an instance of getting the current container.
Up to this point, the singleton mode has been briefly understood. Understanding the singleton mode is also to better understand the container.
Persistence in learning, persistence in blogging, and persistence in sharing are the beliefs that Kaka has always adhered to since its beginning. I hope that Kaka’s articles on the huge Internet can bring you a little bit of help. I’m Kaka, see you next time.
The above is the detailed content of Singleton mode of ThinkPHP container. For more information, please follow other related articles on the PHP Chinese website!