search
HomeBackend DevelopmentPHP TutorialDetailed explanation of ThinkPHP functions: M method and R method

This article mainly introduces the M method and R method about the detailed explanation of ThinkPHP functions. It has a certain reference value. Now I share it with you. Friends in need can refer to it.

First of all, give it to everyone Introducing the detailed explanation of ThinkPHP functions: M method

M method is used to instantiate a basic model class. The difference from D method is:

1. No custom model class is required, reducing IO loading, good performance;

2. After instantiation, only methods in the basic model class (the default is the Model class) can be called;

3. You can Specify the table prefix, database and database connection information when instantiating; the power of the

D method is reflected in how powerful the custom model class you encapsulate is. However, with the new version of the basic model class of the ThinkPHP framework The functions are becoming more and more powerful, and the M method is more and more practical than the D method.

The calling format of the M method:

M('[Basic model name:]Model name','Data table prefix','Database connection information')

Let’s take a look at the specific uses of the M method:

1. Instantiate the basic model (Model) class

When no model is defined, we You can use the following method to instantiate a model class for operation:

//实例化User模型
$User = M('User');
//执行其他的数据操作
$User->select();

This method is the simplest and most efficient, because there is no need to define any model class, so Support cross-project calls. The disadvantage is also that there is no custom model class, so the relevant business logic cannot be written and only basic CURD operations can be completed.

$User = M('User');

is actually equivalent to:

$User = new Model('User');

means operating the think_user table. The M method also has a singleton function like the D method, and it will not be instantiated repeatedly if called multiple times. The model name parameter of the M method will be automatically converted to lowercase when converted into a data table, which means that ThinkPHP's data table naming specification is in all lowercase format.

2. Instantiate other public model classes

The first way to instantiate is because there is no definition of the model class, so it is difficult to encapsulate some additional logical methods, but In most cases, you may just need to extend some common logic, then you can try the following method.

$User = M('CommonModel:User');

The changed usage is actually equivalent to:

$User = new CommonModel('User');

Because of the system model Classes can be loaded automatically, so we do not need to manually import the class library before instantiation. The model class CommonModel must inherit Model. We can define some common logical methods in the CommonModel class, which eliminates the need to define specific model classes for each data table. If your project already has more than 100 data tables, most of them are basic For CURD operations, only some models have some complex business logic that needs to be encapsulated, so the combination of the first method and the second method is a good choice.

3. Pass in table prefix, database and other information

The M method has three parameters. The first parameter is the model name (can include the basic model class and database ), the second parameter is used to set the prefix of the data table (leave blank to take the table prefix of the current project configuration), and the third parameter is used to set the currently used database connection information (leave it blank to take the database connection of the current project configuration) Information), for example:

$User = M('db2.User','think_');

means instantiating the Model model class and operating the think_user table in the db2 database.

If the second parameter is left blank or not passed, it means using the data table prefix in the current project configuration. If the data table being operated does not have a table prefix, you can use:

$User = M('db1.User',null);

means instantiating the Model model class and operating the user table in the db1 database.

If the database you operate requires different user accounts, you can pass in the connection information of the database, for example:

$User = M('User','think_','mysql://user_a:1234@localhost:3306/thinkphp');

represents the basic model class Use Model, then operate the think_user table, use the user_a account to connect to the database, and the operating database is thinkphp.

The third connection information parameter can use DSN configuration or array configuration, and can even support configuration parameters.

For example, if

'DB_CONFIG'=>'mysql://user_a:1234@localhost:3306/thinkphp';

is configured in the project configuration file, you can use:

$User = M('User','think_','DB_CONFIG');

Basic model classes and databases can be used together, for example:

$User = M('CommonModel:db2.User','think_');

If you want to instantiate a hierarchical model, use the public model Class method, we can use:

M('UserLogic:User');

to instantiate UserLogic, although this does not make much sense, because you can use

D('User','Logic');

Achieve the same function.

Detailed explanation of ThinkPHP functions: R method

The R method is used to call the operation method of a certain controller, which is a further enhancement and supplement of the A method. See here for the usage of method A.

R method calling format:

R('[Project://][Group/]Module/Operation','Parameter','Controller layer name')

For example, we define an operation method as:

class UserAction extends Action {
 public function detail($id){
  return M('User')->find($id);
 }
 }

那么就可以通过R方法在其他控制器里面调用这个操作方法(一般R方法用于跨模块调用)

$data = R('User/detail',array('5'));

表示调用User控制器的detail方法(detail方法必须是public类型),返回值就是查询id为5的一个用户数据。如果你要调用的操作方法是没有任何参数的话,第二个参数则可以留空,直接使用:

$data = R('User/detail');

也可以支持跨分组和项目调用,例如:

R('Admin/User/detail',array('5'));

表示调用Admin分组下面的User控制器的detail方法。

R('Admin://User/detail',array('5'));

表示调用Admin项目下面的User控制器的detail方法。

官方的建议是不要在同一层多太多调用,会引起逻辑的混乱,被公共调用的部分应该封装成单独的接口,可以借助3.1的新特性多层控制器,单独添加一个控制器层用于接口调用,例如,我们增加一个Api控制器层,

class UserApi extends Action {
 public function detail($id){
  return M('User')->find($id);
 }
 }

然后,使用R方法调用

$data = R('User/detail',array('5'),'Api');

也就是说,R方法的第三个参数支持指定调用的控制器层。

同时,R方法调用操作方法的时候可以支持操作后缀设置C('ACTION_SUFFIX'),如果你设置了操作方法后缀,仍然不需要更改R方法的调用方式。

以上内容给大家分享了ThinkPHP函数详解之M方法和R方法,希望对大家有所帮助。

相关推荐:

ThinkPHP之R方法实例

The above is the detailed content of Detailed explanation of ThinkPHP functions: M method and R method. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP's Current Status: A Look at Web Development TrendsPHP's Current Status: A Look at Web Development TrendsApr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP vs. Other Languages: A ComparisonPHP vs. Other Languages: A ComparisonApr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and FunctionalityPHP vs. Python: Core Features and FunctionalityApr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: A Key Language for Web DevelopmentPHP: A Key Language for Web DevelopmentApr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

See all articles

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 agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment