This article mainly introduced the THINKPHP5.0 Framework API optimization After the friendly, combined with a specific example of the THINKPHP5.0 framework for API optimization in the data output and error debugging of the friendly improvement, the need for friends can refer to the next
The example of this article describes the THINKPHP5.0 Framework API optimization after the friendliness. Share to everyone for your reference, as follows:
The new thinkphp is optimized for API development and does not rely on the original API schema extensions.
Data output
The new version of the controller output by the Response
class unified processing, rather than directly in the controller output, by setting default_return_type
or dynamically set different types of Response
output can be automatically converted to data processing, generally speaking, you just need to return a string or an array in the controller, For example if we configure:
' Default_return_type ' = ' json '
Then the following controller method return value is 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 Done '];} }
After accessing the request URL address, you can finally see the output in the browser as follows:
Copy the Code code 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 itself does not need to make any changes to the code.
Supports explicitly specifying the output type, such as specifying the JSON data output below:
namespace App\index\controller;class index{public Function Index () { $data = [' name ' = ' thinkphp ', ' URL ' = ' thinkphp.cn ']; Specify JSON data output return JSON ([' data ' = $data, ' code ' =>1, ' message ' = ' Operation Complete ')} }
Optionally, specify the output XML type data:
namespace App\index\controller;class index{public Function Index () { $data = [' name ' = ' thinkphp ', ' URL ' = ' thinkphp.cn ']; Specify the XML data output return XML ([' Data ' = $data, ' code ' =>1, ' message ' = ' operation complete ') }}
The core supported data types include view, XML, JSON, and JSONP, and other types need to be expanded themselves.
Error debugging
Because the API development is not convenient to develop debugging on the client, but the ThinkPHP5 trace debugging function supports socket, which can realize the remote development debugging.
How to set it up:
' App_trace ' + true, ' trace ' = [ ' type ' = ' + ' socket ', //Socket Server ' host ' \ = ' Slog.thinkphp.cn ',],
The chrome plugin is then installed for remote debugging, with detailed reference to the debugging section.