“We talked about the ThinkPHP database query Db method above. Today we will briefly talk about the implementation of the Model class. Method.
”
Preface
Model is also mentioned in the framework Model concept, this usage accounts for the vast majority of framework usage.
Next, Kaka will continue to conduct in-depth analysis of the model based on the above, so now prepare your bench and eat some melon seeds to read this article!
The execution flow chart of the Db class provided above is also released for everyone, so you can familiarize yourself with it.
1. Take a brief look at some usage files of the model
There must be a model directory in the module directory
Then come to the framework At the bottom, you can see the files about the model class. In this class, two knowledge points we have learned before are used.
The first one is that ArrayAccess accesses the properties of the object like an array.
The second feature is the super class (trait), which actually implements a function similar to multiple inheritance, but remember that PHP does not have multiple inheritance, and the two concepts cannot be confused.
Then there is also a model folder at the bottom of the framework. This folder also uses the same functions as the Db class. .
For example, connectors, queries, generators
After a brief understanding, we need to understand the model One of the cases was analyzed, just for the implementation of one case!
2. Analysis of new logic source code for model scenario analysis
This case uses the new actions in the model Case analysis and in-depth analysis of the source code.
First of all, you need to create the model file. Kaka always uses the command line to create files. The advantage of using the command line to create files is to prevent yourself from making mistakes with the namespace when creating files. .
Then implement the first function and use the model to add it. The content of this piece is really very simple, just a few clicks This step is all very basic. Kaka’s main job is to analyze the implementation process for everyone.
The case in the controller is as follows. Pay attention to the way of writing Kaka here.
Let me briefly talk about why Kaka writes it this way and what are the benefits of writing it this way.
First of all, it is essential to introduce the model class.
Then declare a variable
The last step is to assign the model class to the declared variable when the controller is initialized.
Then just use the declared variable when using it. The advantage of this is that it can reduce the amount of modified code when your model name conflicts later.
You can think about a scenario where you pre-define a model name, and then want to change the model name later. At this time, if you follow Kaka's writing method, you only need the controller The content in initialization can be done with one line of code.
Otherwise the entire code needs to be modified, which is why Kaka writes it this way.
Let’s execute it first and see the execution results.
According to the results in the above figure, we can know that there are no problems with the code logic. Next, we will conduct an in-depth analysis of the save method and look at the model. What is the difference from the execution method of Db class?
In-depth analysis of the save method
First of all, you need to understand which file this code will be executed into.
Everyone knows that this$this->userModel is a class in the model Object, then just go directly to this model file and take a look.
In fact, it doesn’t matter whether you read this file or not. Our customized model files must be inherited Model files, which are the files that Kaka showed you at the beginning of this article that will be used in the model.
Then come to the model class at the bottom of the frameworkthinkphp/library/think/Model.php.
You should understand a little bit after seeing this method. Even if you don't read the documentation, you should understand it at once. When the save method has only one parameter, it is added, and when there is a second parameter, it is updated.
Since the parameter given in the Kaka case is an array, the first judgment will not be executed.
Next, we will conduct an in-depth analysis of the check data before writing in this save method.
Next, let’s take a look at what operations this method performs.
According to the above figure, we can know that the parameter passed is an array, which is the data we need to add.
The most important step in the above picture is this line of code$this->setAttr($key, $value, $data);
According to the prompts When Kaka comes to this method, the values of the three parameters have also been printed, so the judgment will not be executed, and only the last step will be taken to set the data object properties.
According to the above figure, the final return result will be returned directly to $this->checkBeforeSave($data, $where) , which is the picture below.
Next about$result = $this->exists ? $this->updateData($ where): $this->insertData($sequence);This line of code needs to be understood carefully.
First of all, you can see the first attribute, which is $this->exists. Are you familiar with this value? Yes, if there is a where condition when checking the data before writing, then will be set to true, please see the picture below
So the code will execute$this->insertData( $sequence)This method, in this method we don’t pay attention to anything, the main focus is how to add data.
Just pay attention to the place circled by Kaka.
Then the code will come to the insert method, in this method$this->parseOptions();Here is the previously analyzed analysis expression (can be used for query or write operations) .
A connector is used here. This connector is an object injected through dependency injection in the constructor of this class.
Then you will come to thinkphp/library/think/db/Connection.php## of this file #insert method.
execute method will be called to execute the SQL statement, because the sql statement has been generated before. In the following, we will start a new section to analyze this method in depth.
builder class and then obtain the bound parameters and clear them. Finally, use the execution operation to execute the sql statement
3. In-depth analysis of the execution of execute
The case is still the case used in the previous section
First of all, we must clarify the parameters of executeThis method, in this The method has three parameters, mainly describing the first and second parameters.
The value of the parameter has been placed in the code comment.
Then analyze step by step, the first thing to do is$this->initConnect(true);Initialization Database Connectivity.
What you need to know in this method is what is being judged here, which is actually what the deploy parameter is.
First of all, it needs to be clear that this parameter must be obtained from the configuration file, and then what we are parsing now is the database. Then this parameter is most likely in the database configuration file.
After analyzing the code, we found this configuration item in the database configuration file. This configuration item is the deployment method of the database.
0 Centralized (single server), 1 Distributed (master-slave server). In this case, or in real project operation, distributed databases will not be used in the framework, so there is no need to understand it. .
Then the code will continue to execute$this->linkID = $this->connect();, that is, the hint given by the comment is the default single database.
Coming to this method, the location where the Kaka screenshot is taken will be used to determine whether the database connection ID supports multiple connections.
Then the second judgment will directly obtain the parameter configuration information and the database configuration file obtained in advance in the constructor of this class, and finally return it to the config attribute.
Next parse the content of the connection parameter block, the content of this block, determine the params index value in the configuration information, this value The configuration file is an empty array, so it returns true.
The second judgment of whether it is an array will also return true.
So this judgment condition is established and the if judgment statement will be executed.
A small knowledge point here is the knowledge about operators and or not .
And: Return true if all conditions are true
Or: Return true as long as one condition is true
The attributes of this class in the above pictureparamshave been declared in advance. Here we only need to use pdo to connect to mysql. parameters.
In order to facilitate your understanding, Kaka has printed this parameter for everyone, please see the picture below.
In other words, the pdo parameters are actually just a series of declared constants.
The next step is to connect to the database using pdo and return the connection information, that is, to $this->linkID, until The initialization of the database connection ends here.
Then it will be executed using the PDo operation instanceexecuteThis method is a built-in method and will eventually return Or affect the number of records.
4. Summary
This section starts with understanding the files required by the model and then adds the behavior to the model. Deep source code parsing behavior.
In the process of parsing the source code, some parts have not been fully explained, but the key parts have been passed through.
Finally, we analyzed the execute method in depth. Why should we analyze this method? Because this method is the last step in the execution of all operations.
“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 In-depth analysis of the model of ThinkPHP database query. For more information, please follow other related articles on the PHP Chinese website!
What Are the Key Features of ThinkPHP's Built-in Testing Framework?Mar 18, 2025 pm 05:01 PMThe article discusses ThinkPHP's built-in testing framework, highlighting its key features like unit and integration testing, and how it enhances application reliability through early bug detection and improved code quality.
How to Use ThinkPHP for Building Real-Time Stock Market Data Feeds?Mar 18, 2025 pm 04:57 PMArticle discusses using ThinkPHP for real-time stock market data feeds, focusing on setup, data accuracy, optimization, and security measures.
What Are the Key Considerations for Using ThinkPHP in a Serverless Architecture?Mar 18, 2025 pm 04:54 PMThe article discusses key considerations for using ThinkPHP in serverless architectures, focusing on performance optimization, stateless design, and security. It highlights benefits like cost efficiency and scalability, but also addresses challenges
How to Implement Service Discovery and Load Balancing in ThinkPHP Microservices?Mar 18, 2025 pm 04:51 PMThe article discusses implementing service discovery and load balancing in ThinkPHP microservices, focusing on setup, best practices, integration methods, and recommended tools.[159 characters]
What Are the Advanced Features of ThinkPHP's Dependency Injection Container?Mar 18, 2025 pm 04:50 PMThinkPHP's IoC container offers advanced features like lazy loading, contextual binding, and method injection for efficient dependency management in PHP apps.Character count: 159
How to Use ThinkPHP for Building Real-Time Collaboration Tools?Mar 18, 2025 pm 04:49 PMThe article discusses using ThinkPHP to build real-time collaboration tools, focusing on setup, WebSocket integration, and security best practices.
What Are the Key Benefits of Using ThinkPHP for Building SaaS Applications?Mar 18, 2025 pm 04:46 PMThinkPHP benefits SaaS apps with its lightweight design, MVC architecture, and extensibility. It enhances scalability, speeds development, and improves security through various features.
How to Build a Distributed Task Queue System with ThinkPHP and RabbitMQ?Mar 18, 2025 pm 04:45 PMThe article outlines building a distributed task queue system using ThinkPHP and RabbitMQ, focusing on installation, configuration, task management, and scalability. Key issues include ensuring high availability, avoiding common pitfalls like imprope


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver CS6
Visual web development tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.
































