Explanation of the request and response processing process in the Yii Framework of PHP. tutorial on yii Framework _ PHP

Source: Internet
Author: User
Tags sendfile
Interpret the request and response processing process in PHP's Yii Framework. Interpreting the processing process of Requests and responses in PHP's Yii Framework. yii Framework I. request (Requests) Requests: Requests of an application are expressed using the yiiwebRequest object, this object provides a process for interpreting requests and responses in PHP's 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: $ 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: $ 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) {/* This request is an AJAX request */} if ($ request-> isGet) {/* The request method is GET */} if ($ request-> isPost) {/* The request method is POST */} if ($ request-> isPut) {/* The 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 the 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. The existing Pragma header is not overwritten. $ Headers-> add ('pragm', 'no-cache'); // you can specify a Pragma header. any existing Pragma header will be discarded $ headers-> set ('pragm', 'no-cache '); // delete the Pragma header and return the value of the deleted Pragma header to the array $ values = $ headers-> remove ('pragm ');

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-SendfileLighttpd v1.4: X-LIGHTTPD-send-fileLighttpd v1.5: X-SendfileNginx: X-Accel-RedirectCherokee: 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

Requests Request: an application Request is represented by the yii \ web \ Request object...

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.