Interpreting the process of request and response in the YII framework of PHP, YII framework _php Tutorial

Source: Internet
Author: User
Tags sendfile

Read the process of request and response in the YII framework of PHP, YII framework


First, request (requests)
Request:
An application request is represented by a Yii\web\request object that provides information such as the request parameter (the translator's note: Usually a get parameter or a post parameter), an HTTP header, a cookie, and so on. By default, for a given request, you can get access to the appropriate request object by requesting Application component application component (an instance of the Yii\web\request Class). In this section, we will show you how to use this component in your application.

1. Request parameters

To get the request parameters, you can call the Yii\web\request::get () method of the requests component and the Yii\web\request::p Ost () method. 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 ']: ';

Info: It is recommended that you get the request parameters as above, rather than accessing $_get and $_post directly, by requesting the component. This makes it easier for you to write test cases because you can forge data to create a mock request component.
When implementing the RESTful APIs interface, you often need to get the arguments that are submitted by the put, patch, or other request methods method. You can get 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 ');

Info: Unlike GET parameters, Post,put,patch, and so on, the arguments that are submitted are sent in the request body. When you access these parameters through the methods described above, the request component parses the parameters. You can customize how these parameters are parsed by configuring Yii\web\request::p the Arsers property.

2. Request method

You can get the HTTP method used by the current request via YII:: $app->request->method expression. A complete set of Boolean properties is also provided to detect that 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) {/* 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 ways to detect the URL of the current request.

Assuming that the requested URL is http://example.com/admin/index.php/product?id=100, you can get the various parts of the URL as described below:

    • Yii\web\request::url: Return/admin/index.php/product?id=100, this URL does not include the host Info section.
    • Yii\web\request::absoluteurl: Returns http://example.com/admin/index.php/product?id=100 that contains the entire URL of host Infode.
    • Yii\web\request::hostinfo: Returns http://example.com, only the host Info section.
    • Yii\web\request::p athinfo: Returns/PRODUCT, which is the part of the entry script that precedes the question mark (the query string).
    • Yii\web\request::querystring: Returns the part of the id=100, after the question mark.
    • Yii\web\request::baseurl: Returns/admin, after host info, before the Entry script section.
    • Yii\web\request::scripturl: Return/admin/index.php, no path info and query string parts.
    • Yii\web\request::servername: Returns the example.com, the host name in the URL.
    • Yii\web\request::serverport: Returns 80, which is the port used in the Web service.

4.HTTP Head

You can get the HTTP header information through the yii\web\headercollection returned by the Yii\web\request::headers property. For example

$headers is a Yii\web\headercollection object $headers = Yii:: $app->request->headers;//Returns the Accept header value $accept = $he Aders->get (' Accept '), if ($headers->has (' user-agent ')) {/* This is a user-agent header */}

The request component also provides a way 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 type that is acceptable to the user. The types returned are sorted according to their quality score. The type with the highest score will be returned first.
    • Yii\web\request::acceptablelanguages: Returns the language acceptable to the user. The languages returned are sorted according to their preference level. The first parameter represents the most preferred language.

If your app supports multiple languages and you want to display the page in the end user's 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 list of languages supported in your app to return to the most appropriate 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 properties and methods of the content negotiation described above.

5. Client Information

You can obtain the host name and the IP address of the client by Yii\web\request::userhost and Yii\web\request::userip respectively, for example,

$userHost = Yii:: $app->request->userhost; $userIP = yii:: $app->request->userip;

Second, response (responses)
Response:
When the app finishes processing a request, it generates a Yii\web\response response object and sends the message to the end user that the Response object contains the HTTP status code, HTTP header, and subject content, and the ultimate purpose of Web application development is essentially to build these response objects based on different requests.

In most cases, the Response application component that inherits from Yii\web\response is mostly handled, however, Yii also allows you to create your own response objects and send them to the end user, which is explained later.

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

1. Status Code

When building a response, the first thing to do is to identify the status of whether the request was successfully processed, by setting the Yii\web\response::statuscode property, which uses a valid HTTP status code. For example, to identify that processing has been successfully processed, you can set the status code to 200 as follows:

Yii:: $app->response->statuscode = 200;

However, in most cases it is not necessary to explicitly set the status code, because the Yii\web\response::statuscode status code defaults to 200, and if you need to specify a request failure, you can throw the corresponding HTTP exception as follows:

throw new \yii\web\notfoundhttpexception;

When the error handler catches an exception, it extracts the status code from the exception and assigns a value to the response, and for the above yii\web\notfoundhttpexception corresponds to the HTTP 404 status Code, the following is the Yii predefined HTTP exception:

    • 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 you want to throw an exception that is not in the list above, create a yii\web\httpexception exception with the status code thrown, as follows:

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

2.HTTP Head

You can manipulate yii\web\response::headers in the response component to send HTTP header information, such as:

$headers = Yii:: $app->response->headers;//Adds a Pragma header, the existing Pragma header will not be overwritten. $headers->add (' Pragma ', ' no-cache ');//Set a PRAGMA header. Any existing Pragma header 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 ');

Supplement: Header name is case sensitive, the newly registered header information before the Yii\web\response::send () method call is not sent to the user.

3. Response body

Most of the responses should have a principal store content that you want to display to the end user.

If you already have a well-formed body string, you can assign a value to the Yii\web\response::content property of the response, for example:

Yii:: $app->response->content = ' Hello world! ';

If you need to format before sending to end users, you should set Yii\web\response::format and Yii\web\response::d ata Property, Yii\web\response::format property specifies Yii\web\ Response::d The formatted style of the data in ATA, for example:

$response = Yii:: $app->response; $response->format = \yii\web\response::format_json; $response->data = [' Message ' = ' and ' Hello World '];

Yii supports the following formats that can be used directly, each of which implements the Yii\web\responseformatterinterface class, which can be customized or added by configuring the Yii\web\response::formatters property.

    • Yii\web\response::format_html: Implemented by Yii\web\htmlresponseformatter.
    • Yii\web\response::format_xml: Implemented by Yii\web\xmlresponseformatter.
    • Yii\web\response::format_json: Implemented by Yii\web\jsonresponseformatter.
    • YII\WEB\RESPONSE::FORMAT_JSONP: Implemented by Yii\web\jsonresponseformatter.

The above response body can be explicitly set, but in most cases it is implicitly set by the return value of the action method, and the common scenario is as follows:

Public Function Actionindex () {return $this->render (' Index ');}

The index operation above returns the result of the index view rendering, and the return value is 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 action method, and if you want to use a different response format, you should format the data before returning it, for example:

Public Function Actioninfo () {\yii:: $app->response->format = \yii\web\response::format_json; return [  ' Message ' = ' Hello World ',  ' code ' = 100,];

As mentioned above, accidents uses the default response application component, can also create its own response object and send it to the end user, which can be returned in the action method as follows:

Public Function Actioninfo () {return \yii::createobject ([  ' class ' = ' Yii\web\response ',  ' format ' = \ Yii\web\response::format_json,  ' data ' = [   ' message ' = ' Hello World ',   ' code ' = [+  ],];}

Note: If you create your own response object, you will not be able to set the response component in the app configuration, however, you can use the dependency injection application generic configuration to your new response object.

4. Browser Jump

Browser jumps rely on sending a location HTTP header, because this feature is usually used and YII provides special support for it.

The Yii\web\response::redirect () method can be called to jump the user's browser to a URL address, which sets the appropriate location header with the specified URL and returns itself as a response object, in which the abbreviated version can be called in the method of Operation Yii\web\ Controller::redirect (), for example:

Public Function Actionold () {return $this->redirect (' http://example.com/new ', 301);}

In the above code, the action method returns the result of the redirect () method, as described previously, the response object returned by the action method is sent to the end user when the total response is made.

In addition to the action method, you can call Yii\web\response::redirect () and call the Yii\web\response::send () method directly to ensure that no other content is appended to the response.

\yii:: $app->response->redirect (' http://example.com/new ', 301)->send ();

Supplement: The Yii\web\response::redirect () method defaults to a response status code of 302, which tells the browser that the requested resource is temporarily placed on another URI address, passing a 301 status code informing the browser that the requested resource has been permanently Redirect to the new Urid address.
If the current request is an AJAX request, sending a location header does not automatically cause the browser to jump, in order to solve this problem, the Yii\web\response::redirect () method sets a value for the x-redirect header of the URL to jump, The client can write JavaScript code to read the header value and then let the browser jump to the corresponding URL.

Add: Yii comes with a yii.js JavaScript file that provides common JavaScript functionality, including X-redirect header-based browser jumps, so if you use this JavaScript file (via Yii\web\yiiasset Resource bundle registration), you do not need to write code for AJAX jumps.

5. Sending files

Similar to browser jumps, file sending is another feature that relies on the specified HTTP header, and Yii provides a collection of methods to support various file-sending requirements, which 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 use the response object as the return value, and if the file to be sent is very large, consider using yii\web\response::sendstreamasfile () because it saves memory, and 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 do not call the file-sending method in the action method, you should also call Yii\web\response::send (), and no additional content is appended to the response.

\yii:: $app->response->sendfile (' Path/to/file.txt ')->send ();

Some browsers offer a special file-sending function called X-sendfile, which, in principle, jumps the request to a file on the server, and the Web app ends before the server sends the file, calling Yii\web\response::xsendfile () to use the feature. Here is a brief list of how some popular Web servers enable the X-sendfile feature:

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

The content in the response before the Yii\web\response::send () method call is not sent to the user, which is automatically called by default at the end of the Yii\base\application::run (), although the method can be explicitly called to force a response to be sent immediately.

The Yii\web\response::send () method uses the following steps to send a response:

    • Triggers the Yii\web\response::event_before_send event.
    • Call Yii\web\response::p repare () to format yii\web\response::d ATA is yii\web\response::content.
    • Triggers 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
    • Triggers the Yii\web\response::event_after_send event.

Once the Yii\web\response::send () method is executed, calling the method elsewhere is ignored, which means that once the response is emitted, no additional content can be appended.

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

Articles you may be interested in:

    • The definition and binding methods of behavior in the YII framework of PHP
    • A detailed approach to using behavioral behaviors in the PHP yii framework
    • In-depth explanation of properties in the Yii framework of PHP
    • PHP's YII framework uses database configuration and SQL Operations example tutorials
    • Examples of how to do error and exception handling in the PHP yii framework
    • Parsing of PHP in the YII framework of the cookie and session function related operations
    • A brief analysis of the basic knowledge of the modular mechanism of the YII framework of PHP
    • Examples of extensions to the Yiibase portal class in the PHP yii framework
    • The operation mechanism and routing function of the YII framework of PHP
    • In-depth parsing of event events mechanism in the YII framework of PHP
    • Full interpretation of the log function in the YII framework of PHP
    • The method of removing the binding behavior of a component in PHP's YII framework

http://www.bkjia.com/PHPjc/1111910.html www.bkjia.com true http://www.bkjia.com/PHPjc/1111910.html techarticle interpreting the request and response processing flow in the YII framework of PHP, YII framework One, request (requests) Request: An application request is represented by an Yii\web\request object that provides ...

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