Detailed explanation of D method example of ThinkPHP3.1

  • 2021-07-01 07:01:04
  • OfStack

D method should be used more methods, used to instantiate custom model classes, is an encapsulation of ThinkPHP framework to instantiate Model classes, and implements singleton mode, supporting cross-project and grouping calls, and the call format is as follows:

D ('[Project://] [Grouping/] Model', 'Model Layer Name')

The return value of the method is the instantiated model object.

The D method can automatically detect model classes. If there is a custom model class, it instantiates the custom model class. If it does not exist, it instantiates the Model base class. At the same time, the instantiated model will not be instantiated repeatedly.

The most common use of the D method is to instantiate a custom model of the current project, such as:


//  Instantiation User Model 
$User = D('User');

The Lib/Model/UserModel. class. php file under the current project is imported, and then the UserModel class is instantiated, so the actual code may be equivalent to the following:


import('@.Model.UserModel');
$User = new UserModel();

However, if the D method is used, if the UserModel class does not exist, it will be automatically called


new Model('User');

And the second call does not need to be instantiated again, which can reduce the object instantiation overhead of 1.

The D method can support cross-grouping and project instantiation models, such as:


// Instantiation Admin Project's User Model 
D('Admin://User')
 // Instantiation Admin Grouped User Model 
D('Admin/User')

Note: To implement the cross-project invocation model, you must ensure that the directory structures of the two projects are juxtaposed.

Since version 3.1 of ThinkPHP, the D method can also instantiate other models due to the addition of hierarchical model support, such as:


//  Instantiation UserService Class 
$User = D('User','Service');
 //  Instantiation UserLogic Class 
$User = D('User','Logic');

And D ('User', 'Service'); Lib/Service/UserService. class. php is imported and instantiated, equivalent to the following code:


import('@.Service.UserService');
$User = new UserSerivce();

Related articles: