Understanding the process of request and response in PHP's YII framework _php skills

Source: Internet
Author: User
Tags sendfile yii

I. Request (Requests)
Request:
An application request is represented by a Yii\web\request object that provides information such as a request parameter (a translator note: Usually a get parameter or post parameter), HTTP headers, cookies, and so on. By default, for a given request, you can access the corresponding Request object by requesting application component the application component (an instance of the Yii\web\request Class). In this section, we will describe how to use this component in your application.

1. Request parameters

To get the request parameters, you can invoke the Yii\web\request::get () method of the request 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 ']: ';

Information: It is recommended that you get request parameters as described above, rather than direct access to $_get and $_post. This makes it easier 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 obtain parameters submitted via put, patch, or other request methods requests. You can get these parameters by calling the Yii\web\request::getbodyparam () method. For example

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

Returns all parameters
$params = $request->bodyparams;

Returns the parameter "id"
$param = $request->getbodyparam (' id ');

Info: 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 methods described above, the request component resolves the parameters. You can customize how these parameters are parsed by configuring Yii\web\request::p arsers properties.

2. Request method

You can get the HTTP method that the current request uses by using Yii:: $app->request->method expression. A set of Boolean properties is also provided here 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->is Post) {/* Request method is post
/} if ($request->isput) {/* Request method is put//}

3. Request URLs

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

Assuming 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 containing the entire URL of the host Infode.
    • Yii\web\request::hostinfo: Back to http://example.com, only the host Info section.
    • Yii\web\request::p athinfo: Returns/PRODUCT, which is the part of the query string that follows the entry script after the question mark.
    • Yii\web\request::querystring: Returns the portion of the id=100 after the question mark.
    • Yii\web\request::baseurl: Returns the section before the entry script after/admin, host info.
    • Yii\web\request::scripturl: Back to/admin/index.php, no path info and query string part.
    • Yii\web\request::servername: Returns 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 from 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 = $headers->get (' Accept ');

if ($headers->has (' user-agent ')) {/* This is a user-agent head */}

The request component also provides a way to support quick access to common headers, including:

    • Yii\web\request::useragent: Return 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 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 levels. The first parameter represents the most preferred language.

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 returns the most appropriate language by comparing the yii\web\request::acceptablelanguages in the list of languages supported in your application.

Tip: You can also use the Yii\filters\contentnegotiator filter to dynamically determine which content types and languages should be used in response. This filter implements the properties and methods of the content negotiation described above.

5. Client Information

You can get the host name and the client's IP address separately through Yii\web\request::userhost and Yii\web\request::userip, for example,

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

Ii. Response (responses)
Response:
When the application completes processing a request, it generates a Yii\web\response response object and sends it to the end user The Response object contains the HTTP status code, the HTTP header and the main content, etc., the ultimate purpose of Web application development is essentially to build these response objects according to different requests.

In most cases, the main processing inherited from Yii\web\response Response application components, however, Yii also allows you to create your own response object to the end user, which will be elaborated later.

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

1. Status Code

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

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, and if you need to specify a request failure, you can throw the corresponding HTTP exception, as follows:

throw new \yii\web\notfoundhttpexception;

When an error handler catches an exception, it extracts the status code from the exception and assigns a value to the response, which corresponds to the HTTP 404 status code for the above yii\web\notfoundhttpexception, and the following are predefined HTTP exceptions for 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 you want to throw an exception that is not in the list above, you can create a yii\web\httpexception exception with a 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, for example:

$headers = Yii:: $app->response->headers;

Add a Pragma header and the existing Pragma header will not be overwritten.
$headers->add (' Pragma ', ' No-cache ');

Set a Pragma header. Any existing Pragma head will be discarded
$headers->set (' Pragma ', ' No-cache ');

Deletes the PRAGMA header and returns the value of the deleted Pragma header to the array
$values = $headers->remove (' Pragma ');

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

3. Response subject

Most of the responses should have a body that stores what you want to display to the end user.

If you 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 Properties, Yii\web\response::format properties Specify Yii\web\ Response::d ATA-formatted style of 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 implementing the Yii\web\responseformatterinterface class, either by customizing these formatters or by configuring the Yii\web\response::formatters property to add the formatter.

    • Yii\web\response::format_html: Through the yii\web\htmlresponseformatter to achieve.
    • Yii\web\response::format_xml: Through the yii\web\xmlresponseformatter to achieve.
    • Yii\web\response::format_json: Through the yii\web\jsonresponseformatter to achieve.
    • YII\WEB\RESPONSE::FORMAT_JSONP: Through the yii\web\jsonresponseformatter to achieve.

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

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

The above index operation 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 ' =>,
 ];
}

As described above, accidents uses the default response application component, or creates its own response object and sends it to the end user, which can be returned in an 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 application configuration, however, you can use a dependency injection to apply the generic configuration to your new response object.

4. Browser Jump

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

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

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

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

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

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

Add: The Yii\web\response::redirect () method defaults to setting the response status code to 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 for 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 X-redirect header that values the URL to jump to. The client can write JavaScript code to read the header value and then let the browser jump the corresponding URL.

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

5. Send the file

Like a browser jump, file sending is another feature that relies on a 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 (): Sends an existing file stream as a file to the client

Each of these methods takes 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 operation:

Public Function Actiondownload ()
{return
 \yii:: $app->response->sendfile (' path/to/file.txt ');
}

If you are not calling a file-sending method in an action method, you should call Yii\web\response::send () later, 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 feature named X-sendfile, which is the principle of jumping the request to a file on the server where the Web application ends before the server sends the file, and to invoke Yii\web\response::xsendfile () to use the feature. The following is a brief list of how some common Web servers enable X-sendfile features:

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

The content in the response before the Yii\web\response::send () method call is not sent to the user, which is automatically invoked by default at the end of Yii\base\application::run (), though the method can be explicitly invoked to force the 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 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, meaning that once the response is sent, no additional content can be appended.

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

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.