Explanation of the request and Response Processing Process in the PHP Yii framework.
1. Request (Requests)
Request:
An application Request is represented by a yii \ web \ Request object, which provides Request parameters such as GET or POST parameters), HTTP header, cookies, and other information. By default, for a given request, you can access the corresponding Request object through the request application component (yii \ web \ Request class instance. This section describes how to use this component in your application.
1. Request Parameters
To obtain request parameters, you can call the yii \ web \ Request: get () method and yii \ web \ Request: post () method of the request component. They return the values of $ _ GET and $ _ POST respectively. For example,
$ request = Yii :: $ app-> request;
$ get = $ request-> get ();
// equivalent to: $ get = $ _GET;
$ id = $ request-> get ('id');
// equivalent to: $ id = isset ($ _ GET ['id'])? $ _GET ['id']: null;
$ id = $ request-> get ('id', 1);
// equivalent to: $ id = isset ($ _ GET ['id'])? $ _GET ['id']: 1;
$ post = $ request-> post ();
// equivalent to: $ post = $ _POST;
$ name = $ request-> post ('name');
// equivalent to: $ name = isset ($ _ POST ['name'])? $ _POST ['name']: null;
$ name = $ request-> post ('name', '');
// equivalent to: $ name = isset ($ _ POST ['name'])? $ _POST ['name']: '';
Information: We recommend that you use the request component as above to obtain request parameters, instead of directly accessing $ _ GET and $ _ POST. This makes it easier for you to write test cases, because you can forge data to create a simulated request component.
When implementing the RESTful APIs interface, you often need to obtain parameters submitted through PUT, PATCH or other request methods. You can obtain these parameters by calling the yii \ web \ Request: getBodyParam () method. For example,
$ request = Yii :: $ app-> request;
// return all parameters
$ params = $ request-> bodyParams;
// return parameter "id"
$ param = $ request-> getBodyParam ('id');
Information: Unlike GET parameters, POST, PUT, PATCH, and so on, these submitted parameters are sent in the Request body. When you access these parameters through the method described above, the request component will parse these parameters. You can customize how to parse these parameters by configuring the yii \ web \ Request: parsers attribute.
2. Request Method
You can use the Yii: $ app-> request-> method Expression to obtain the HTTP method used by the current request. A complete set of Boolean attributes are provided to check whether the current request is of a certain type. For example,
$ request = Yii :: $ app-> request;
if ($ request-> isAjax) {/ * The request is an AJAX request * /}
if ($ request-> isGet) {/ * The request method is GET * /}
if ($ request-> isPost) {/ * Request method is POST * /}
if ($ request-> isPut) {/ * request method is PUT * /}
3. request URLs
The request component provides many methods to detect the URL of the current request.
Suppose the requested URL is a http://example.com/admin/index.php/product? Id = 100. You can obtain all the parts of the URL as described below:
- Yii \ web \ Request: url:/admin/index. php/product? Id = 100. This URL does not include host info.
- Yii \ web \ Request: absoluteUrl: Return http://example.com/admin/index.php/product? Id = 100, including the whole URL of host infode.
- Yii \ web \ Request: hostInfo: returns the http://example.com, only the host info section.
- Yii \ web \ Request: pathInfo: return/product. This is the part before the question mark (query string) after the entrance script.
- Yii \ web \ Request: queryString: returns the part with id = 100, followed by a question mark.
- Yii \ web \ Request: baseUrl: return/admin, after host info, before the script entry.
- Yii \ web \ Request: scriptUrl: returns/admin/index. php without path info and query string.
- Yii \ web \ Request: serverName: Return example.com, host name in URL.
- Yii \ web \ Request: serverPort: Return 80, which is the port used in the web service.
4. HTTP Header
You can obtain the HTTP header information through the yii \ web \ HeaderCollection returned by the yii \ web \ Request: headers attribute. For example,
// $ headers is a yii \ web \ HeaderCollection object
$ headers = Yii :: $ app-> request-> headers;
// return Accept header value
$ accept = $ headers-> get ('Accept');
if ($ headers-> has ('User-Agent')) {/ * This is a User-Agent header * /}
The request component also provides methods to quickly access common headers, including:
- Yii \ web \ Request: userAgent: the User-Agent header is returned.
- Yii \ web \ Request: contentType: return the value of the Content-Type header. Content-Type is the MIME Type data in the Request body.
- Yii \ web \ Request: acceptableContentTypes: the MIME type of the content that is acceptable to the user. The types returned are sorted by their quality scores. The type with the highest score will be returned first.
- Yii \ web \ Request: acceptableLanguages: return the language acceptable to the user. The returned languages are sorted by their preferred levels. The first parameter indicates the language with the highest priority.
If your application supports multiple languages and you want to display pages in your favorite language, you can use the language negotiation method yii \ web \ Request: getPreferredLanguage (). This method uses yii \ web \ Request: acceptableLanguages to compare and filter the Supported languages in your application and return the most suitable language.
Tip: You can also use the yii \ filters \ ContentNegotiator filter to dynamically determine which content types and languages should be used in the response. This filter implements the attributes and methods of the content negotiation described above.
5. Client Information
You can use yii \ web \ Request: userHost and yii \ web \ Request: userIP to obtain the IP addresses of the host name and client respectively, for example,
$userHost = Yii::$app->request->userHost;$userIP = Yii::$app->request->userIP;
2. Response)
Response:
After an application completes processing a request, it will generate a yii \ web \ Response object and send it to the end user Response object. The information contained in the Response object includes the HTTP status code, HTTP header, and body content, the ultimate goal of Web application development is to build these response Objects Based on different requests.
In most cases, it mainly handles Response Application Components inherited from yii \ web \ response. However, Yii allows you to create your own Response objects and send them to end users, this will be explained later.
This section describes how to build a response and send it to end users.
1. Status Code
When building a Response, the first thing to do is to identify whether the request is successfully processed. You can set the yii \ web \ Response: statusCode attribute to use a valid HTTP status code. For example, to identify that the process has been processed successfully, you can set the status code to 200, as shown below:
Yii::$app->response->statusCode = 200;
However, you do not need to explicitly set the status code in most cases, because the yii \ web \ Response: statusCode status code is 200 by default. If you need to specify a request failure, you can throw an HTTP exception as follows:
throw new \yii\web\NotFoundHttpException;
When the error processor detects an exception, it extracts the status code from the exception and assigns a value to the response. For the preceding yii \ web \ NotFoundHttpException, it corresponds to the HTTP 404 status code, the following are pre-defined HTTP exceptions of Yii:
- Yii \ web \ BadRequestHttpException: status code 400.
- Yii \ web \ ConflictHttpException: status code 409.
- Yii \ web \ ForbiddenHttpException: status code 403.
- Yii \ web \ GoneHttpException: status code 410.
- Yii \ web \ MethodNotAllowedHttpException: status code 405.
- Yii \ web \ NotAcceptableHttpException: status code 406.
- Yii \ web \ NotFoundHttpException: status code 404.
- Yii \ web \ ServerErrorHttpException: status code 500.
- Yii \ web \ TooManyRequestsHttpException: status code 429.
- Yii \ web \ UnauthorizedHttpException: status code 401.
- Yii \ web \ UnsupportedMediaTypeHttpException: status code 415.
If the exception to be thrown is not in the above list, you can create a yii \ web \ HttpException with A status code to throw it, as shown below:
throw new \yii\web\HttpException(402);
2. HTTP Header
You can control yii \ web \ response: headers in the Response component to send HTTP header information, for example:
$ headers = Yii :: $ app-> response-> headers;
// Add a Pragma header. Existing Pragma headers will not be overwritten.
$ headers-> add ('Pragma', 'no-cache');
// Set a Pragma header. Any existing Pragma headers will be discarded
$ headers-> set ('Pragma', 'no-cache');
// delete the Pragma header and return the value of the deleted Pragma header to an array
$ values = $ headers-> remove ('Pragma');
The header name is case-sensitive. Newly registered header information before the yii \ web \ Response: send () method is called is not sent to the user.
3. response body
Most responses should have a subject to store the content you want to display to end users.
If a formatted subject string already exists, you can assign a value to the yii \ web \ Response: content attribute of the Response, for example:
Yii::$app->response->content = 'hello world!';
If you need to format the format before sending it to the end user, set the yii \ web \ Response: format and yii \ web \ Response: data attributes, yii \ web \ Response :: the format attribute specifies the formatted style of data in yii \ web \ Response: data, for example:
$response = Yii::$app->response;
$response->format = \yii\web\Response::FORMAT_JSON;
$response->data = ['message' => 'hello world'];
Yii supports the following formats that can be used directly. Each of which implements the yii \ web \ ResponseFormatterInterface class can be customized or configured by yii \ web \ Response :: formatters attribute to add the formatter.
- Yii \ web \ Response: FORMAT_HTML: implemented through yii \ web \ HtmlResponseFormatter.
- Yii \ web \ Response: FORMAT_XML: implemented through yii \ web \ XmlResponseFormatter.
- Yii \ web \ Response: FORMAT_JSON: implemented through yii \ web \ JsonResponseFormatter.
- Yii \ web \ Response: FORMAT_JSONP: implemented through yii \ web \ JsonResponseFormatter.
The above response body can be explicitly set, but in most cases it is implicitly set through the return value of the operation method. Common scenarios are as follows:
public function actionIndex()
{
return $this->render('index');
}
The preceding index operation returns the index view rendering result. The returned value is formatted by the response component and sent to the end user.
Because the default Response format is yii \ web \ Response: FORMAT_HTML, you only need to return a string in the operation method. To use other Response formats, you should set the format before returning data, for example:
public function actionInfo()
{
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return [
'message' => 'hello world',
'code' => 100,
];
}
As described above, a lightning mine uses the default response Application Component, you can also create your own response object and send it to the end user. You can return this response object in the operation method, as shown below:
public function actionInfo()
{
return \Yii::createObject([
'class' => 'yii\web\Response',
'format' => \yii\web\Response::FORMAT_JSON,
'data' => [
'message' => 'hello world',
'code' => 100,
],
]);
}
Note: If you create your own response object, you will not be able to set the response component in the application configuration. However, you can use the dependency injection application universal configuration to your new response object.
4. browser jump
Browser redirection relies on sending a Location HTTP header, because this function is usually used, Yii provides special support for it.
You can call the yii \ web \ Response: redirect () method to redirect your browser to a URL address. This method sets the appropriate Location header with the specified URL and returns its own Response object, in the operation method, you can call the abbreviated yii \ web \ Controller: redirect (), for example:
public function actionOld()
{
return $this->redirect('http://example.com/new', 301);
}
In the above Code, the operation method returns the result of the redirect () method. As described above, the response object returned by the operation method will be sent to the end user as a total response.
In addition to the operation method, you can directly call yii \ web \ Response: redirect () and then call yii \ web \ Response: send () method to ensure that no other content is appended to the response.
\Yii::$app->response->redirect('http://example.com/new', 301)->send();
Supplement: by default, the yii \ web \ Response: redirect () method sets the Response status code to 302, which tells the browser to temporarily place the requested resource on another URI address, you can pass a 301 status code to notify the browser that the requested resource has been permanently redirected to the new URId address.
If the current request is an AJAX request, sending a Location header will not automatically redirect the browser. To solve this problem, yii \ web \ Response: redirect () method to set an X-Redirect header for the URL to be redirected. You can write JavaScript code on the client to read the header value and then Redirect the browser to the corresponding URL.
Supplement: Yii is equipped with a yii. javaScript files provide common JavaScript Functions, including browser redirection Based on the X-Redirect header. Therefore, if you use this JavaScript file (registered through yii \ web \ YiiAsset resource package ), you do not need to write AJAX jump code.
5. Send files
Similar to browser redirection, File Sending is another function that relies on the specified HTTP header. Yii provides a method set to support various File Sending requirements. They have built-in support for HTTP headers.
- Yii \ web \ Response: sendFile (): Send an existing file to the client
- Yii \ web \ Response: sendContentAsFile (): send a text string to the client as a file
- Yii \ web \ Response: sendStreamAsFile (): sends an existing file stream to the client as a file
These methods use the Response object as the return value. If the file to be sent is very large, you should consider using yii \ web \ Response: sendStreamAsFile () because it saves more memory, the following example shows how to send a file in the Controller operation:
public function actionDownload()
{
return \Yii::$app->response->sendFile('path/to/file.txt');
}
If the file sending method is not called in the operation method, yii \ web \ Response: send () should also be called later. No other content is appended to the Response.
\Yii::$app->response->sendFile('path/to/file.txt')->send();
Some browsers provide a special file sending function named X-Sendfile. The principle is to redirect requests to files on the server. Web applications can end before the server sends files. To use this function, you can call yii \ web \ Response: xSendFile () to briefly list how some common Web servers enable the X-Sendfile function:
Apache: X-Sendfile
Lighttpd v1.4: X-LIGHTTPD-send-file
Lighttpd v1.5: X-Sendfile
Nginx: X-Accel-Redirect
Cherokee: X-Sendfile and X-Accel-Redirect
6. Send a response
Content in the Response before the yii \ web \ Response: send () method is called is not sent to the user. This method is automatically called at the end of yii \ base \ Application: run () by default, however, you can call this method explicitly to force an immediate response.
The yii \ web \ Response: send () method uses the following steps to send a Response:
- Trigger the yii \ web \ Response: EVENT_BEFORE_SEND event.
- Call yii \ web \ Response: prepare () to format yii \ web \ Response: data as yii \ web \ Response: content.
- Trigger the yii \ web \ Response: EVENT_AFTER_PREPARE event.
- Call yii \ web \ Response: sendHeaders () to send the registered HTTP Header
- Call yii \ web \ Response: sendContent () to send the Response body content
- Trigger the yii \ web \ Response: EVENT_AFTER_SEND event.
Once the yii \ web \ Response: send () method is executed, calling this method elsewhere will be ignored, which means that once the Response is sent, no additional content can be appended.
As you can see, yii \ web \ Response: send () triggers several practical events, which can be adjusted or packaged by responding to these events.
Articles you may be interested in:
- Definition and binding of behavior in PHP Yii framework
- Detailed description of Behaviors in PHP Yii framework
- In-depth explanation of attributes in PHP Yii framework)
- Tutorial on using database configuration and SQL operations in PHP Yii framework
- The example explains how to handle errors and exceptions in the PHP Yii framework.
- Parse related operations of cookie and session functions in PHP Yii framework
- Brief Analysis of basic knowledge about componentization mechanism of PHP Yii framework
- Example of YiiBase entry class extension in the Yii framework of PHP
- Describes the operating mechanism and routing function of the Yii framework of PHP.
- In-depth analysis of event mechanism in PHP Yii framework
- A comprehensive explanation of the log function in the PHP Yii framework
- How to remove the behavior bound to a component from the Yii framework of PHP