ThinkPHP function M method, R method, and U method usage

Source: Internet
Author: User
Tags db2 lowercase

First, we will introduce ThinkPHP Function details: M method

 

The M method is used to instantiate a basic model class. The difference between the M method and the D method is:

1. You do not need to customize model classes to reduce I/O loading and improve performance;

2. After instantiation, you can only call methods in the basic Model class (default: Model class;

3. You can specify the table prefix, database and database connection information during instantiation;

The strength of the D method is reflected in the strength of your encapsulated custom model classes. However, as the basic model classes of the new ThinkPHP framework become more and more powerful, the M method is more and more practical than the D method.

M method call format:

M ('[basic model name:] model name', 'data table prefix', 'database connection information ')

Let's take a look at the specific usage of the M method:

1. Instantiate the basic Model class

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


// Instantiate the User model
$ User = M ('user ');
// Perform other data operations
$ User-> select ();


This method is the simplest and most efficient. Because no model class needs to be defined, cross-project calls are supported. The disadvantage is that there is no custom model class, so you cannot write the relevant business logic and can only perform basic CURD operations.


$ User = M ('user ');


In fact, it is equivalent:


$ User = new Model ('user ');


Operation on the think_user table. The M method and the D method also have the singleton function. Multiple calls will not be instantiated repeatedly. The model name parameter of the M method is automatically converted to lowercase when converted to a data table. That is to say, the data table naming rules of ThinkPHP are in full lowercase format.

2. Instantiate other public model classes

The first method of instantiation is difficult to encapsulate some additional logic methods because there is no definition of the model class. However, in most cases, it may only need to expand some general logic, then you can try the following method.


$ User = M ('commonmodel: user ');


The switching method is actually equivalent:


$ User = new CommonModel ('user ');


Because the system model classes can be automatically loaded, we do not need to manually import class libraries before instantiation. The Model class CommonModel must inherit the Model. We can define some common logical methods in the CommonModel class to avoid defining specific model classes for each data table. If your project has more than 100 data tables, in most cases, there are some basic CURD operations, but some models have complicated business logic to be encapsulated. Therefore, the combination of the first method and the second method is a good choice.

3. Input the table prefix, database, and other information.

The M method has three parameters. The first parameter is the model name (which can include the basic model class and database ), the second parameter is used to set the prefix of the data table (if left blank, the prefix of the table configured in the current project is used ), the third parameter is used to set the currently used database connection information (if left blank, the database connection information configured in the current project is used). For example:


$ User = M ('db2. User', 'think _');


Instantiate the Model class and operate the think_user table in the db2 database.

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


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


Instantiate the Model class and operate the user table in the db1 database.

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


$ User = M ('user', 'think _ ', 'MySQL: // user_a: 1234 @ localhost: 3306/thinkphp ');


The base Model class uses the Model, and then performs operations on the think_user table. The user_a account is used to connect to the database, and the operation database is thinkphp.

The third connection information parameter can be configured using DSN or array, or even configuration parameters.

For example, in the project configuration file, configure:


'Db _ config' => 'MySQL: // user_a: 1234 @ localhost: 3306/thinkphp ';


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 layered model, you can use the public model class:


M ('userlogic: user ');


To instantiate UserLogic, although this is of little significance, because it can be used


D ('user', 'logic ');


Implement the same function.

 

ThinkPHP function description: R method

 

The R method is used to call the operation method of A controller. It is further enhanced and supplemented by Method. For the usage of Method A, see here.

Call Format of the R method:

R ('[ project: //] [group/] module/operation', 'parameters', 'Controller layer name ')

For example, we define an operation method as follows:


Class UserAction extends Action {
Public function detail ($ id ){
Return M ('user')-> find ($ id );
 } 
 } 


Then you can call this operation method in other controllers using the R method (generally, the R method is used for cross-module calls)


$ Data = R ('user/detail', array ('5 '));


It indicates that the detail method of the User controller is called (the detail method must be of the public type), and the return value is to query a User data whose id is 5. If the operation method you want to call does not have any parameters, you can leave the second parameter blank and use it directly:


$ Data = R ('user/detail ');


Cross-group and Project calls are also supported, for example:


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


Call the detail method of the User controller under the Admin group.


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


Call the detail method of the User controller under the Admin project.

The official suggestion is not to call too many on the same layer, which may cause logical confusion. The public call part should be encapsulated into a separate interface, and the new features of 3.1 can be used for multi-layer controllers, add a controller layer for interface calling. For example, we add an Api controller layer,


Class UserApi extends Action {
Public function detail ($ id ){
Return M ('user')-> find ($ id );
 } 
 } 


Then, use the R method to call


$ Data = R ('user/detail', array ('5'), 'api ');


That is to say, the third parameter of the R method supports specifying the called controller layer.

At the same time, when the R method calls the operation method, you can set the operation suffix c ('Action _ SUFFIX '). If you have set the operation method SUFFIX, you do not need to change the calling method of the R method.

 

U method Usage example:

 

U ('user/add') // Generate the add operation address of the User module

You can also support group calls:

U ('Home/User/add') // Generate the add operation address for the User module of the Home group

Of course, you can only write the operation name to call the current module

U ('ADD') // Generate the add operation address of the current access module

In addition to group, module, and operation name, we can also input some parameters:

U ('blog/read? Id = 1') // The URL of the read operation that generates the Blog module and whose id is 1

The second parameter of the U method supports the input parameter and the array and string defining methods. If the parameter is just a string, it can be defined in the first parameter. The following methods are equivalent:

U ('blog/cate', array ('Cate _ id' => 1, 'status' => 1 ))
U ('blog/cate', 'Cate _ id = 1 & status = 1 ')
U ('blog/cate? Cate_id = 1 & status = 1 ')

However, the following definition is not allowed to pass parameters:

U ('blog/cate/cate_id/1/status/1 ')

According to different URL settings of the project, the same U method call can intelligently correspond to different URL address effects, for example:

U ('blog/read? Id = 1 ')

This definition is used as an example.
If the current URL is set to normal mode, the last generated URL address is:

Http: // serverName/index. php? M = Blog & a = read & id = 1

If the current URL is set to PATHINFO, the last URL generated by the same method is:

Http: // serverName/index. php/Blog/read/id/1

If the current URL is set to REWRITE mode, the last URL generated by the same method is:

Http: // serverName/Blog/read/id/1

If you have also set the PATHINFO separator:

'URL _ PATHINFO_DEPR '=> '_'

Will generate

Http: // serverName/Blog_read_id_1

If the current URL is set to REWRITE mode and the pseudo-static suffix is set to html, the last URL generated by the same method is:

Http: // serverName/Blog/read/id/1.html

If multiple pseudo-static parameters are supported, the first pseudo-static suffix is automatically added to the end of the URL, of course, you can also manually specify the pseudo-static suffix to be generated in the U method, for example:

U ('blog/read', 'id = 1', 'xml ')

Will generate

Http: // serverName/Blog/read/id/1.xml

Route support
The U method can also support routing. If we define a routing rule:

'News/: id \ d' => 'news/read'

You can use

U ('/news/1 ')

The generated URL is:

Http: // serverName/index. php/news/1

Domain name support
If your application involves the operation addresses of multiple subdomain names, you can also specify the domain name to generate the address in the U method, for example:

U ('blog/read@blog.thinkphp.cn ', 'id = 1 ');

@ Enter the domain name to be specified.

In addition, if the 5th parameter of the U method is set to true, it indicates that the current domain name is automatically recognized, and APP_SUB_DOMAIN_DEPLOY and APP_SUB_DOMAIN_RULES are automatically set based on the sub-domain name deployment.
If URL_CASE_INSENSITIVE is enabled, all lower-case URLs are generated.
Anchor support

Starting from version 3.1.2, the U method can also generate the anchor in the URL address, for example:

U ('blog/read # comment', 'id = 1', 'html ')

Will generate

Http: // serverName/Blog/read/id/1.html # comment

If both the domain name and the anchor are used, pay attention to the order of the domain name after the anchor. For example:

U ('blog/read # comment @ Blog ', 'id = 1 ');

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.