Interpreting the request and response processing process in PHP Yii Framework

Source: Internet
Author: User
Tags sendfile
This article mainly introduces the request and response processing process in the PHP Yii Framework, which is also the most basic function of Yii processing website background. For more information, see 1. request (Requests)
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: It is recommended that you obtain the request parameters through the request component as above, instead of directly accessing $ _GET and $ _POST. This makes it easier for you to write test cases because you can fake data to create a mock request component.
When implementing the RESTful APIs interface, you often need to get the parameters submitted by PUT, PATCH or other request methods. You can get these parameters by calling the yii \ web \ Request :: getBodyParam () method. E.g,

$ request = Yii :: $ app-> request;

// return all parameters
$ params = $ request-> bodyParams;

// return parameter "id"
$ param = $ request-> getBodyParam ('id');

Information: Unlike GET parameters, POST, PUT, PATCH, etc. These submitted parameters are sent in the request body. When you access these parameters through the methods described above, the request component will parse these parameters. You can customize how to parse these parameters by configuring the yii \ web \ Request :: parsers property.

2. Request method

You can use Yii :: $ app-> request-> method expression to get the HTTP method used by the current request. There is also a set of Boolean properties used to detect if the current request is of a certain type. E.g,

$ request = Yii :: $ app-> request;

if ($ request-> isAjax) {/ * The request is an AJAX request * /}
if ($ request-> isGet) {/ * The request method is GET * /}
if ($ request-> isPost) {/ * The request method is POST * /}
if ($ request-> isPut) {/ * request method is PUT * /}

3. Request URLs

The request component provides many ways to detect the URL of the current request.

Assuming the requested URL is, you can get the parts of the URL as described below:

yii \ web \ Request :: url: returns /admin/index.php/product?id=100, this URL does not include the host info part.
yii \ web \ Request :: absoluteUrl: returns, which contains the entire URL of host infode.
yii \ web \ Request :: hostInfo: returns, only the host info part.
yii \ web \ Request :: pathInfo: returns / product, this is the part after the entry script and before the question mark (query string).
yii \ web \ Request :: queryString: returns id = 100, the part after the question mark.
yii \ web \ Request :: baseUrl: after returning / admin, host info, before the entry script.
yii \ web \ Request :: scriptUrl: returns /admin/index.php, without path info and query string parts.
yii \ web \ Request :: serverName: returns the host name in, URL.
yii \ web \ Request :: serverPort: returns 80, which is the port used in the web service.
4.HTTP header

You can get the HTTP header information through the yii \ web \ HeaderCollection returned by the yii \ web \ Request :: headers property. E.g,

// $ 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 support quick access to common headers, including:

yii \ web \ Request :: userAgent: returns the User-Agent header.
yii \ web \ Request :: contentType: Returns the value of the Content-Type header. Content-Type is the MIME type data in the request body.
yii \ web \ Request :: acceptableContentTypes: Returns the content MIME types that are acceptable to the user. The returned types are sorted by their quality score. The highest scoring type will be returned first.
yii \ web \ Request :: acceptableLanguages: returns languages acceptable to users. The languages returned are sorted according to their preference hierarchy. The first parameter represents the language with the highest priority.
If your application supports multiple languages and you want to display pages in the end user's favorite language, then you can use the language negotiation method yii \ web \ Request :: getPreferredLanguage (). This method uses yii \ web \ Request :: acceptableLanguages to compare and filter the list of supported languages in your application and return the most suitable languages.

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 properties and methods of content negotiation described above.

5. Client Information

You can obtain the host name and the client's IP address through yii \ web \ Request :: userHost and yii \ web \ Request :: userIP, for example,

$ userHost = Yii :: $ app-> request-> userHost;
$ userIP = Yii :: $ app-> request-> userIP;

Second, the response (Responses)
When the application finishes processing a request, it will generate a yii \ web \ Response response object and send it to the end user. The response object contains information such as HTTP status codes, HTTP headers, and body content. The ultimate purpose of web application development is essentially based on Different requests construct these response objects.

In most cases, it mainly deals with the response application component inherited from yii \ web \ Response. However, Yii also allows you to create your own response object and send it to the end user, which will be explained later.

In this section, we will describe how to construct the response and send it to the end user.

Status code

When constructing the response, the first thing to do is to identify the status of the request's successful processing. You can set the yii \ web \ Response :: statusCode property, which uses 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, in most cases, you do not need to explicitly set the status code, because the yii \ web \ Response :: statusCode status code defaults to 200. If you need to specify that the request fails, you can throw the corresponding HTTP exception, as shown below:

throw new \ yii \ web \ NotFoundHttpException;
When an error handler catches an exception, it will extract the status code from the exception and assign it to the response. For the above yii \ web \ NotFoundHttpException corresponding to the HTTP 404 status code, the following is the predefined HTTP exception 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 you want to throw is not in the above list, you can create a yii \ web \ HttpException and throw it with the status code, as follows:

throw new \ yii \ web \ HttpException (402);

2.HTTP header

You can manipulate yii \ web \ Response :: headers in the response component to send HTTP headers, 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 the array
$ values = $ headers-> remove ('Pragma');

Added: The header name is case sensitive. The newly registered header information is not sent to the user before the yii \ web \ Response :: send () method is called.

3. Response body

Mostly the response should have a body that stores what you want to display to the end user.

If you already have a formatted body string, you can assign it to the yii \ web \ Response :: content property of the response, for example:

Yii :: $ app-> response-> content = 'hello world!';
If formatting is required before sending to the end user, set the yii \ web \ Response :: format and yii \ web \ Response :: data attributes, yii \ web \

The Response :: format property specifies the format of the 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 implements the yii \ web \ ResponseFormatterInterface class. You can customize these formatters or add formatters by configuring the yii \ web \ Response :: formatters property.

yii \ web \ Response :: FORMAT_HTML: via yii \ web \ HtmlResponseFormatter.
yii \ web \ Response :: FORMAT_XML: via yii \ web \ XmlResponseFormatter.
yii \ web \ Response :: FORMAT_JSON: via yii \ web \ JsonResponseFormatter.
yii \ web \ Response :: FORMAT_JSONP: via yii \ web \ JsonResponseFormatter.
The above response body can be set explicitly, but in most cases it is implicitly set by the return value of the operation method. Common scenarios are as follows:

public function actionIndex ()
 return $ this-> render ('index');
The above index operation returns the rendering result of the index view. The returned value will be formatted by the response component and sent to the end user.

Because the response format defaults to yii \ web \ Response :: FORMAT_HTML, you only need to return a string in the operation method. If you want to use other response formats, you should set the format before returning the data, for example:

public function actionInfo ()
 \ Yii :: $ app-> response-> format = \ yii \ web \ Response :: FORMAT_JSON;
 return [
  'message' => 'hello world',
  'code' => 100,
As mentioned above, Mine uses the default response application component, or you can create your own response object and send it to the end user. You can return the 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 dependency injection to apply the common configuration to your new response object.

4. Browser jump

Browser redirection relies on sending a Location HTTP header, as this feature is commonly used and Yii provides special support for it.

You can call the yii \ web \ Response :: redirect () method to redirect the user's browser to a URL address. This method sets the appropriate Location header with the specified URL and returns itself as the response object. In the operation method, you can Call the short version of yii \ web \ Controller :: redirect (), for example:

public function actionOld ()
 return $ this-> redirect ('', 301);
In the above code, the operation method returns the result of the redirect () method. As mentioned earlier, the response object returned by the operation method will be sent to the end user as the total response.

In addition to the operation method, you can directly call yii \ web \ Response :: redirect () and then call the yii \ web \ Response :: send () method to ensure that nothing else is appended to the response.

\ Yii :: $ app-> response-> redirect ('', 301)-> send ();
Added: The yii \ web \ Response :: redirect () method will set the response status code to 302 by default. This status code will tell the browser to temporarily place the requested resource on another URI address. You can pass a 301 status code to inform the browser 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, the yii \ web \ Response :: redirect () method sets an X-Redirect header for the URL to be redirected On the client side, you can write JavaScript code to read the header value and let the browser jump to the corresponding URL.

Added: Yii is equipped with a yii.js JavaScript file to provide common JavaScript functions, including browser redirection based on the X-Redirect header, so if you use this JavaScript file (registered through the yii \ web \ YiiAsset resource package), it will Need to write AJAX jump code.

5. Send the file

Similar to browser jumps, file sending is another feature that relies on specifying HTTP headers. Yii provides a set of methods 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 as a file to the client
yii \ web \ Response :: sendStreamAsFile (): send an existing file stream as a file to the client
These methods all take 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 is more memory efficient. The following example shows how to send a file in a controller action:

public function actionDownload ()
 return \ Yii :: $ app-> response-> sendFile ('path / to / file.txt');
If you did not call the file send method in the action method, you should also call yii \ web \ Response :: send () in the future with nothing else appended to the response.

\ Yii :: $ app-> response-> sendFile ('path / to / file.txt')-> send ();
Some browsers provide a special file sending function called X-Sendfile. The principle is to redirect the request to a file on the server. The web application can end before the server sends the file. :: xSendFile (). Here is a brief list of 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 response

The content of the response will not be sent to the user before the yii \ web \ Response :: send () method is called. This method is automatically called by default at the end of yii \ base \ Application :: run (). However, this method can be called explicitly Force 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.
Fire the yii \ web \ Response :: EVENT_AFTER_PREPARE event.
Call yii \ web \ Response :: sendHeaders () to send the registered HTTP headers
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 other content can be appended.

As you can see, yii \ web \ Response :: send () triggers several useful events. You can adjust or wrap the response by responding to these events.

Related Article

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: 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.