Home >Backend Development >PHP Tutorial >Detailed explanation of ThinkPHP's R method examples_PHP tutorial
ThinkPHP’s R method is used to call the operation method of a certain controller, which is a further enhancement and supplement to the A method.
R method calling format:
R('[Project://][Group/]Module/Operation','Parameters','Controller layer name')
For example, we define an operation method as:
class UserAction extends Action { public function detail($id){ return M('User')->find($id); } }
Then you can call this operation method in other controllers through the R method (generally the R method is used for cross-module calls)
$data = R('User/detail',array('5'));
means calling the detail method of the User controller (the detail method must be of public type), and the return value is to query user data with ID 5. If the operation method you want to call does not have any parameters, the second parameter can be left blank and used directly:
$data = R('User/detail');
can also support cross-group and project calls, for example:
R('Admin/User/detail',array('5'));
indicates calling the detail method of the User controller under the Admin group.
R('Admin://User/detail',array('5'));
indicates calling the detail method of the User controller under the Admin project.
The official recommendation is not to make too many calls on the same layer, otherwise it will cause logical confusion. The publicly called parts should be encapsulated into separate interfaces, which can be added separately with the help of the new feature of ThinkPHP3.1 multi-layer controller. A controller layer is used for interface calls. 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 call
$data = R('User/detail',array('5'),'Api');
In other words, the third parameter of the R method supports specifying the controller layer of the call.
At the same time, the R method can support the operation suffix setting C ('ACTION_SUFFIX') when calling the operation method. If you set the operation method suffix, you still do not need to change the calling method of the R method.