RESTful introduction and YII2 restful how to configure

Source: Internet
Author: User
Tags object serialization php and ticket yii

RESTful introduction and YII2 restful how to configure

The name of rest, "presentation Layer State Transformation", omits the subject. The "presentation layer" actually refers to the "presentation layer" of resources.
Academically speaking:
RESTful's original intention is to consider that software research focuses on the classification of software design and the evolution of design methods.
Rarely objectively evaluates the impact of different design choices on system behavior. On the contrary, network research focuses on the details of communication behavior between systems,
How to improve the performance of a particular communication mechanism often ignores the fact that changing the interactive style of the application has a greater impact on overall performance than changing the interactive protocol.
The author's idea is to understand and evaluate the architecture design of web-based application software on the premise of conforming to the principle of architecture, and to get a strong function, good performance and suitable communication architecture (this passage is not quite understood.) )

What is restful?
The popular understanding is that restful is a logical data API, a logical data interface. By restful this interface, we can realize a powerful and superior system architecture, and provide relevant logical data operations for the applications above other terminal devices. So what is logical data? Logical data is logically derived from the actual abstract data, such as buying a ticket online, for the ticket data. It is represented in the database by the ID of several field tickets Baiche the driving time of the ticket price. But we generally abstract it into a simple noun ticket once the operation of the ticket is naturally in the background to operate these several fields. is not a bit like the object.
(1) All the logical data in the restful can be located by a unique URL, which means that the logical data can be obtained by using the URL, so long as there is a corresponding URL locator identifier, the corresponding logical data is determined.
(2) All logical data is operated through the actions of the HTTP protocol, such as get POST put DELETE

Design standards
There is not yet a strict unified restful standard, but there are several principles
1. Each URI represents a logical resource
2.API should be friendly to programmers, URLs are simple and meaningful. and easy to enter in the browser address bar. That must beautify the path.
3. Clients operate on server-side logical resources through HTTP verbs
4. There should be sufficient flexibility to support the top-level UI. (The API is the background programmer's UI, and like any other UI, you have to think carefully about its user experience.) )
5. Logical resources should be nouns rather than verbs, since the operation of this logical data is contained in the HTTP verb.

Example of a few URL visits
Scenario: Query ticket to Server get/tickets
Query specific tickets to the server get/tickets?tickets_id=1
Purchase specific tickets to the server post/myticket?tickets_id=1
Refund to Server delete/myticket?tickets_id=1


RESTful in the framework of YII2
1. Introduction:
YII provides a complete set of APIs to simplify the implementation of RESTful-style Web service services
YII supports the following APIs about the RESTful style
Rapid prototyping to support common APIs for Active record classes
Response format involved (JSON and XML is supported by default)
Support for custom object serialization with optional output fields
Data acquisition and validation errors in the appropriate format
Support HATEOAS
Efficient routing with appropriate HTTP verb checking
Support for built-in options and head verbs
Certification and authorization
Data caching and HTTP caching
Rate limit


2. Configure restful in Yii2
(1) Add the. htaccess file under Basic/web
Note that the file does not have a file name, or. htaccess is his file name, this form of file is normal, under Windows is not generated, so need some special method, here a little bit.
A. Use DOS command: Copy con. htaccess after the screen Edit command, enter content, and finally press Ctrl+z to finish editing,
succeeded in generating. htaccess;
B. Save directly through the text editing tool, such as Notepad, UltraEdit, and so on, but when you save it, select all the files.
C. Open Windows Notepad---file-> Save As---Select the all file type in the Save as type Drop-down menu that you saved as---Enter in file name. htaccess---Save
The main function of htaccess is that the access URL will not be handed to index.php because the Urlmanager is opened. So need. htaccess according to the access URL, to the Division of labor (personal opinion), when a visit over,. htaccess file analysis access to the file or directory in the URL exists, if there is a direct access to the destination file delivery, if not exist, delivery to the index.php processing. The contents of the htaccess file are as follows:

Rewriteengine
 on # If a directory or a file exists, use it directly
 Rewritecond%{request_filename}!-f
 Rewrit Econd%{request_filename}!-d
 # Otherwise forward it to index.php rewriterule
 . index.php
(2) Configure Urlmanager:
Then we need to configure the Urlmanager in the config/web.php, why should we configure this? Basic has been commented out before.
The reason is that before we directly through the URL to access a controller under the function format is: localhost/basic/web/index.php?r=controllerxx/actionxx This form of access is cumbersome, difficult to detect errors, increase the length of the code, fuzzy. Urlmanager is to solve this problem, that is, manage access to the standard format URL, after use we can save index.php and will be the path. The new access format is as follows: Localhost/basic/web/controllerxx/actionxx. In this urlmanager we set the rules Class=>yii\rest\urlrule because we need to enable restful in yii2, and we must also specify which controllers are the ones that match the restful access. Remember, Urlmanager is written in components[]. The contents are as follows:

' Urlmanager ' => [
       ' Enableprettyurl ' => true,//whether to optimize the URL, that is, the path 1
       ' Showscriptname ' => false,// Whether to omit the index.php
       ' enablestrictparsing ' => false,//to strictly parse the request, to function
       ' rules ' enableprettyurl when used => [     
	  ' class ' => ' yii\rest\urlrule ',//This sentence is to be added because the default in the Urlmanager class is
	  ' controller ' => [' v1/table ', ' V1/login '] ,//Set RESTful API, set module ID to V1 controller table,login as API],
       
 
Special Note: In this example, the two controller table login under the V1 of a module module is set to the RESTful API, which can be set as the controller of the RESTful API in practical use.

(3) Configure enable JSON input:

Request=>[] Array in config/web.php add JSON parsing class parsers=>[]

' Request ' => ['
	       cookievalidationkey ' => ' 098udfhfj ',
	       ' parsers ' => [
			      ' Application/json ' => ' Yii\web\jsonparser ',
			    ]
             ]
With less parsers=>[the],restful API will only be able to distinguish between application/x-www-form-urlencoded and multipart/form-data input formats. The Application/json format can be recognized when added.


In this yii2, restful configuration is finished. The following sections explain how to write RESTful API controllers and how to test calls.



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.