ThinkPHP5.0 framework API-friendly analysis after optimization, thinkphp5.0api
This article describes the friendliness of thinkPHP5.0 framework API after optimization. We will share this with you for your reference. The details are as follows:
The new ThinkPHP version has made many optimizations for API development and does not rely on the original API mode extension.
Data Output
New controller outputResponse
Class, instead of directly outputting data in the controller.default_return_type
Or dynamically set different typesResponse
The output can automatically convert the data. Generally, you only need to return strings or arrays in the Controller. For example, if we configure:
'default_return_type'=>'json'
The return values of the following Controller method are automatically converted to json format and returned.
Namespace app \ index \ controller; class Index {public function index () {$ data = ['name' => 'thinkphp', 'url' => 'thinkphp. cn ']; return ['data' => $ data, 'code' => 1, 'message' => 'Operation completed'];}
After accessing the request URL, you can see the following output in the browser:
Copy codeThe code is as follows: {"data": {"name": "thinkphp", "url": "thinkphp.cn"}, "code": 1, "message ": "\ u64cd \ u4f5c \ u5b8c \ u6210 "}
If you need to return other data formats, the Controller's Code does not need to be changed.
You can specify the output type explicitly. For example, you can specify the JSON data output as follows:
Namespace app \ index \ controller; class Index {public function index () {$ data = ['name' => 'thinkphp', 'url' => 'thinkphp. cn ']; // return json (['data' => $ data, 'code' => 1, 'message' => 'Operation completed ']);}
Or specify the output XML data type:
Namespace app \ index \ controller; class Index {public function index () {$ data = ['name' => 'thinkphp', 'url' => 'thinkphp. cn ']; // specify the return xml (['data' => $ data, 'code' => 1, 'message' => 'Operation completed ']);}
Data Types supported by the core include view, xml, json, and jsonp. For other types, you need to expand them by yourself.
Error debugging
Because API development is not convenient for development and debugging on the client, the Trace debugging function of ThinkPHP5 supports Socket and remote development and debugging.
Setting method:
'App _ track' => true, 'track' => ['type' => 'socket ', // socket server 'host' => 'slog .thinkphp.cn',],
After installing the chrome browser plug-in, you can perform remote debugging. For more information, see the debugging section.