国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
Interpretation of the request and response processing flow in PHP's Yii framework, yii framework
您可能感興趣的文章:
Home Backend Development PHP Tutorial Interpret the request and response processing flow in PHP's Yii framework, yii framework_PHP tutorial

Interpret the request and response processing flow in PHP's Yii framework, yii framework_PHP tutorial

Jul 12, 2016 am 08:56 AM
php php framework yii

Interpretation of the request and response processing flow in PHP's Yii framework, yii framework

1. Requests
Request:
An application request is represented by a yiiwebRequest object, which provides information such as request parameters (Translator's Note: usually GET parameters or POST parameters), HTTP headers, cookies and other information. By default, for a given request, you can obtain access to the corresponding request object through the request application component application component (an instance of the yiiwebRequest class). In this chapter, we will introduce how to use this component in your application.

1. Request parameters

To get request parameters, you can call the yiiwebRequest::get() method and yiiwebRequest::post() method of the request component. They return the values ??of $_GET and $_POST respectively. For example,

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

$get = $request->get(); 
// 等價于: $get = $_GET;

$id = $request->get('id'); 
// 等價于: $id = isset($_GET['id']) ? $_GET['id'] : null;

$id = $request->get('id', 1); 
// 等價于: $id = isset($_GET['id']) ? $_GET['id'] : 1;

$post = $request->post(); 
// 等價于: $post = $_POST;

$name = $request->post('name'); 
// 等價于: $name = isset($_POST['name']) ? $_POST['name'] : null;

$name = $request->post('name', ''); 
// 等價于: $name = isset($_POST['name']) ? $_POST['name'] : '';

Information: It is recommended that you obtain 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 RESTful APIs, you often need to obtain parameters submitted through PUT, PATCH or other request methods. You can get these parameters by calling the yiiwebRequest::getBodyParam() method. For example,

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

// 返回所有參數(shù)
$params = $request->bodyParams;

// 返回參數(shù) "id"
$param = $request->getBodyParam('id');

Information: Unlike GET parameters, POST, PUT, PATCH, etc. 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 these parameters are parsed by configuring the yiiwebRequest::parsers property.

2. Request method

You can get the HTTP method used by the current request through the Yii::$app->request->method expression. A set of Boolean attributes are also provided here to detect whether the current request is of a certain type. For example,

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

if ($request->isAjax) { /* 該請求是一個 AJAX 請求 */ }
if ($request->isGet) { /* 請求方法是 GET */ }
if ($request->isPost) { /* 請求方法是 POST */ }
if ($request->isPut) { /* 請求方法是 PUT */ }

3. Request URLs

The

request component provides many ways to detect the currently requested URL.

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:

  • yiiwebRequest::url: Returns /admin/index.php/product?id=100, this URL does not include the host info part.
  • yiiwebRequest::absoluteUrl: Returns http://example.com/admin/index.php/product?id=100, the entire URL including host infode.
  • yiiwebRequest::hostInfo: Returns http://example.com, only the host info part.
  • yiiwebRequest::pathInfo: Returns /product. This is the part after the entry script and before the question mark (query string).
  • yiiwebRequest::queryString: Returns id=100, the part after the question mark.
  • yiiwebRequest::baseUrl: Returns the part after /admin, host info and before the entry script.
  • yiiwebRequest::scriptUrl: Returns /admin/index.php, without path info and query string parts.
  • yiiwebRequest::serverName: Return example.com, the host name in the URL.
  • yiiwebRequest::serverPort: Returns 80, which is the port used in the web service.

4.HTTP header

You can obtain HTTP header information through the yiiwebHeaderCollection returned by the yiiwebRequest::headers property. For example,

// $headers 是一個 yii\web\HeaderCollection 對象
$headers = Yii::$app->request->headers;

// 返回 Accept header 值
$accept = $headers->get('Accept');

if ($headers->has('User-Agent')) { /* 這是一個 User-Agent 頭 */ }

The request component also provides methods to quickly access common headers, including:

  • yiiwebRequest::userAgent: Returns the User-Agent header.
  • yiiwebRequest::contentType: Returns the value of the Content-Type header. Content-Type is the MIME type data in the request body.
  • yiiwebRequest::acceptableContentTypes: Returns content MIME types acceptable to the user. Returned types are ordered by their quality score. The type with the highest score will be returned first.
  • yiiwebRequest::acceptableLanguages: Returns languages ??acceptable to the user. The languages ??returned are ordered by their preference hierarchy. The first parameter represents the most preferred language.

If your application supports multiple languages ??and you want to display the page in the end user's favorite language, then you can use the language negotiation method yiiwebRequest::getPreferredLanguage(). This method uses yiiwebRequest::acceptableLanguages ??to compare and filter the list of languages ??supported in your application and return the most suitable language.

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

5. Client information

You can obtain the host name and client IP address through yiiwebRequest::userHost and yiiwebRequest::userIP respectively, for example,

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

二、響應(yīng)(Responses)
響應(yīng):
當應(yīng)用完成處理一個請求后, 會生成一個yii\web\Response響應(yīng)對象并發(fā)送給終端用戶 響應(yīng)對象包含的信息有HTTP狀態(tài)碼,HTTP頭和主體內(nèi)容等, 網(wǎng)頁應(yīng)用開發(fā)的最終目的本質(zhì)上就是根據(jù)不同的請求構(gòu)建這些響應(yīng)對象。

在大多是情況下主要處理繼承自 yii\web\Response 的 response 應(yīng)用組件, 盡管如此,Yii也允許你創(chuàng)建你自己的響應(yīng)對象并發(fā)送給終端用戶,這方面后續(xù)會闡述。

在本節(jié),將會描述如何構(gòu)建響應(yīng)和發(fā)送給終端用戶。

1.狀態(tài)碼

構(gòu)建響應(yīng)時,最先應(yīng)做的是標識請求是否成功處理的狀態(tài),可通過設(shè)置 yii\web\Response::statusCode 屬性,該屬性使用一個有效的HTTP 狀態(tài)碼。例如,為標識處理已被處理成功, 可設(shè)置狀態(tài)碼為200,如下所示:

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

盡管如此,大多數(shù)情況下不需要明確設(shè)置狀態(tài)碼,因為 yii\web\Response::statusCode 狀態(tài)碼默認為200, 如果需要指定請求失敗,可拋出對應(yīng)的HTTP異常,如下所示:

throw new \yii\web\NotFoundHttpException;

當錯誤處理器 捕獲到一個異常,會從異常中提取狀態(tài)碼并賦值到響應(yīng), 對于上述的 yii\web\NotFoundHttpException 對應(yīng)HTTP 404狀態(tài)碼,以下為Yii預定義的HTTP異常:

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

如果想拋出的異常不在如上列表中,可創(chuàng)建一個yii\web\HttpException異常,帶上狀態(tài)碼拋出,如下:

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

2.HTTP 頭部

可在 response 組件中操控yii\web\Response::headers來發(fā)送HTTP頭部信息,例如:

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

// 增加一個 Pragma 頭,已存在的Pragma 頭不會被覆蓋。
$headers->add('Pragma', 'no-cache');

// 設(shè)置一個Pragma 頭. 任何已存在的Pragma 頭都會被丟棄
$headers->set('Pragma', 'no-cache');

// 刪除Pragma 頭并返回刪除的Pragma 頭的值到數(shù)組
$values = $headers->remove('Pragma');

補充: 頭名稱是大小寫敏感的,在yii\web\Response::send()方法調(diào)用前新注冊的頭信息并不會發(fā)送給用戶。

3.響應(yīng)主體

大多是響應(yīng)應(yīng)有一個主體存放你想要顯示給終端用戶的內(nèi)容。

如果已有格式化好的主體字符串,可賦值到響應(yīng)的yii\web\Response::content屬性,例如:

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

如果在發(fā)送給終端用戶之前需要格式化,應(yīng)設(shè)置 yii\web\Response::format 和 yii\web\Response::data 屬性,yii\web\Response::format 屬性指定yii\web\Response::data中數(shù)據(jù)格式化后的樣式,例如:

$response = Yii::$app->response;
$response->format = \yii\web\Response::FORMAT_JSON;
$response->data = ['message' => 'hello world'];

Yii支持以下可直接使用的格式,每個實現(xiàn)了yii\web\ResponseFormatterInterface 類, 可自定義這些格式器或通過配置yii\web\Response::formatters 屬性來增加格式器。

  • yii\web\Response::FORMAT_HTML: 通過 yii\web\HtmlResponseFormatter 來實現(xiàn).
  • yii\web\Response::FORMAT_XML: 通過 yii\web\XmlResponseFormatter來實現(xiàn).
  • yii\web\Response::FORMAT_JSON: 通過 yii\web\JsonResponseFormatter來實現(xiàn).
  • yii\web\Response::FORMAT_JSONP: 通過 yii\web\JsonResponseFormatter來實現(xiàn).

上述響應(yīng)主體可明確地被設(shè)置,但是在大多數(shù)情況下是通過 操作 方法的返回值隱式地設(shè)置,常用場景如下所示:

public function actionIndex()
{
 return $this->render('index');
}

上述的 index 操作返回 index 視圖渲染結(jié)果,返回值會被 response 組件格式化后發(fā)送給終端用戶。

因為響應(yīng)格式默認為yii\web\Response::FORMAT_HTML, 只需要在操作方法中返回一個字符串, 如果想使用其他響應(yīng)格式,應(yīng)在返回數(shù)據(jù)前先設(shè)置格式,例如:

public function actionInfo()
{
 \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
 return [
  'message' => 'hello world',
  'code' => 100,
 ];
}

如上所述,觸雷使用默認的 response 應(yīng)用組件,也可創(chuàng)建自己的響應(yīng)對象并發(fā)送給終端用戶,可在操作方法中返回該響應(yīng)對象,如下所示:

public function actionInfo()
{
 return \Yii::createObject([
  'class' => 'yii\web\Response',
  'format' => \yii\web\Response::FORMAT_JSON,
  'data' => [
   'message' => 'hello world',
   'code' => 100,
  ],
 ]);
}

注意: 如果創(chuàng)建你自己的響應(yīng)對象,將不能在應(yīng)用配置中設(shè)置 response 組件,盡管如此, 可使用 依賴注入 應(yīng)用通用配置到你新的響應(yīng)對象。

4.瀏覽器跳轉(zhuǎn)

瀏覽器跳轉(zhuǎn)依賴于發(fā)送一個Location HTTP 頭,因為該功能通常被使用,Yii提供對它提供了特別的支持。

可調(diào)用yii\web\Response::redirect() 方法將用戶瀏覽器跳轉(zhuǎn)到一個URL地址,該方法設(shè)置合適的 帶指定URL的 Location 頭并返回它自己為響應(yīng)對象,在操作的方法中,可調(diào)用縮寫版yii\web\Controller::redirect(),例如:

public function actionOld()
{
 return $this->redirect('http://example.com/new', 301);
}

在如上代碼中,操作的方法返回redirect() 方法的結(jié)果,如前所述,操作的方法返回的響應(yīng)對象會被當總響應(yīng)發(fā)送給終端用戶。

除了操作方法外,可直接調(diào)用yii\web\Response::redirect() 再調(diào)用 yii\web\Response::send() 方法來確保沒有其他內(nèi)容追加到響應(yīng)中。

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

補充: yii\web\Response::redirect() 方法默認會設(shè)置響應(yīng)狀態(tài)碼為302,該狀態(tài)碼會告訴瀏覽器請求的資源 臨時 放在另一個URI地址上,可傳遞一個301狀態(tài)碼告知瀏覽器請求的資源已經(jīng) 永久 重定向到新的URId地址。
如果當前請求為AJAX 請求,發(fā)送一個 Location 頭不會自動使瀏覽器跳轉(zhuǎn),為解決這個問題, yii\web\Response::redirect() 方法設(shè)置一個值為要跳轉(zhuǎn)的URL的X-Redirect 頭, 在客戶端可編寫JavaScript 代碼讀取該頭部值然后讓瀏覽器跳轉(zhuǎn)對應(yīng)的URL。

補充: Yii 配備了一個yii.js JavaScript 文件提供常用JavaScript功能,包括基于X-Redirect頭的瀏覽器跳轉(zhuǎn), 因此,如果你使用該JavaScript 文件(通過yii\web\YiiAsset 資源包注冊),就不需要編寫AJAX跳轉(zhuǎn)的代碼。

5.發(fā)送文件

和瀏覽器跳轉(zhuǎn)類似,文件發(fā)送是另一個依賴指定HTTP頭的功能,Yii提供方法集合來支持各種文件發(fā)送需求,它們對HTTP頭都有內(nèi)置的支持。

  • yii\web\Response::sendFile(): 發(fā)送一個已存在的文件到客戶端
  • yii\web\Response::sendContentAsFile(): 發(fā)送一個文本字符串作為文件到客戶端
  • yii\web\Response::sendStreamAsFile(): 發(fā)送一個已存在的文件流作為文件到客戶端

這些方法都將響應(yīng)對象作為返回值,如果要發(fā)送的文件非常大,應(yīng)考慮使用 yii\web\Response::sendStreamAsFile() 因為它更節(jié)約內(nèi)存,以下示例顯示在控制器操作中如何發(fā)送文件:

public function actionDownload()
{
 return \Yii::$app->response->sendFile('path/to/file.txt');
}

如果不是在操作方法中調(diào)用文件發(fā)送方法,在后面還應(yīng)調(diào)用 yii\web\Response::send() 沒有其他內(nèi)容追加到響應(yīng)中。

\Yii::$app->response->sendFile('path/to/file.txt')->send();

一些瀏覽器提供特殊的名為X-Sendfile的文件發(fā)送功能,原理為將請求跳轉(zhuǎn)到服務(wù)器上的文件, Web應(yīng)用可在服務(wù)器發(fā)送文件前結(jié)束,為使用該功能,可調(diào)用yii\web\Response::xSendFile(), 如下簡要列出一些常用Web服務(wù)器如何啟用X-Sendfile 功能:

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.發(fā)送響應(yīng)

在yii\web\Response::send() 方法調(diào)用前響應(yīng)中的內(nèi)容不會發(fā)送給用戶,該方法默認在yii\base\Application::run() 結(jié)尾自動調(diào)用,盡管如此,可以明確調(diào)用該方法強制立即發(fā)送響應(yīng)。

yii\web\Response::send() 方法使用以下步驟來發(fā)送響應(yīng):

  • 觸發(fā) yii\web\Response::EVENT_BEFORE_SEND 事件.
  • 調(diào)用 yii\web\Response::prepare() 來格式化 yii\web\Response::data 為 yii\web\Response::content.
  • 觸發(fā) yii\web\Response::EVENT_AFTER_PREPARE 事件.
  • 調(diào)用 yii\web\Response::sendHeaders() 來發(fā)送注冊的HTTP頭
  • 調(diào)用 yii\web\Response::sendContent() 來發(fā)送響應(yīng)主體內(nèi)容
  • 觸發(fā) yii\web\Response::EVENT_AFTER_SEND 事件.

一旦yii\web\Response::send() 方法被執(zhí)行后,其他地方調(diào)用該方法會被忽略, 這意味著一旦響應(yīng)發(fā)出后,就不能再追加其他內(nèi)容。

如你所見yii\web\Response::send() 觸發(fā)了幾個實用的事件,通過響應(yīng)這些事件可調(diào)整或包裝響應(yīng)。

您可能感興趣的文章:

  • PHP的Yii框架中行為的定義與綁定方法講解
  • 詳解在PHP的Yii框架中使用行為Behaviors的方法
  • 深入講解PHP的Yii框架中的屬性(Property)
  • PHP的Yii框架中使用數(shù)據(jù)庫的配置和SQL操作實例教程
  • 實例講解如何在PHP的Yii框架中進行錯誤和異常處理
  • 解析PHP的Yii框架中cookie和session功能的相關(guān)操作
  • 簡要剖析PHP的Yii框架的組件化機制的基本知識
  • PHP的Yii框架中YiiBase入口類的擴展寫法示例
  • 詳解PHP的Yii框架的運行機制及其路由功能
  • 深入解析PHP的Yii框架中的event事件機制
  • 全面解讀PHP的Yii框架中的日志功能
  • PHP的Yii框架中移除組件所綁定的行為的方法

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1111910.htmlTechArticleInterpretation of the processing flow of requests and responses in PHP's Yii framework, yii framework 1. Requests (Requests) Request: a Application requests are represented by yiiwebRequest objects, which provide...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Applying Semantic Structure with article, section, and aside in HTML Applying Semantic Structure with article, section, and aside in HTML Jul 05, 2025 am 02:03 AM

The rational use of semantic tags in HTML can improve page structure clarity, accessibility and SEO effects. 1. Used for independent content blocks, such as blog posts or comments, it must be self-contained; 2. Used for classification related content, usually including titles, and is suitable for different modules of the page; 3. Used for auxiliary information related to the main content but not core, such as sidebar recommendations or author profiles. In actual development, labels should be combined and other, avoid excessive nesting, keep the structure simple, and verify the rationality of the structure through developer tools.

The requested operation requires elevation Windows The requested operation requires elevation Windows Jul 04, 2025 am 02:58 AM

When you encounter the prompt "This operation requires escalation of permissions", it means that you need administrator permissions to continue. Solutions include: 1. Right-click the "Run as Administrator" program or set the shortcut to always run as an administrator; 2. Check whether the current account is an administrator account, if not, switch or request administrator assistance; 3. Use administrator permissions to open a command prompt or PowerShell to execute relevant commands; 4. Bypass the restrictions by obtaining file ownership or modifying the registry when necessary, but such operations need to be cautious and fully understand the risks. Confirm permission identity and try the above methods usually solve the problem.

How to handle File Uploads securely in PHP? How to handle File Uploads securely in PHP? Jul 08, 2025 am 02:37 AM

To safely handle PHP file uploads, you need to verify the source and type, control the file name and path, set server restrictions, and process media files twice. 1. Verify the upload source to prevent CSRF through token and detect the real MIME type through finfo_file using whitelist control; 2. Rename the file to a random string and determine the extension to store it in a non-Web directory according to the detection type; 3. PHP configuration limits the upload size and temporary directory Nginx/Apache prohibits access to the upload directory; 4. The GD library resaves the pictures to clear potential malicious data.

How Do You Pass Variables by Value vs. by Reference in PHP? How Do You Pass Variables by Value vs. by Reference in PHP? Jul 08, 2025 am 02:42 AM

InPHP,variablesarepassedbyvaluebydefault,meaningfunctionsorassignmentsreceiveacopyofthedata,whilepassingbyreferenceallowsmodificationstoaffecttheoriginalvariable.1.Whenpassingbyvalue,changestothecopydonotimpacttheoriginal,asshownwhenassigning$b=$aorp

PHP find the position of the last occurrence of a substring PHP find the position of the last occurrence of a substring Jul 09, 2025 am 02:49 AM

The most direct way to find the last occurrence of a substring in PHP is to use the strrpos() function. 1. Use strrpos() function to directly obtain the index of the last occurrence of the substring in the main string. If it is not found, it returns false. The syntax is strrpos($haystack,$needle,$offset=0). 2. If you need to ignore case, you can use the strripos() function to implement case-insensitive search. 3. For multi-byte characters such as Chinese, the mb_strrpos() function in the mbstring extension should be used to ensure that the character position is returned instead of the byte position. 4. Note that strrpos() returns f

PHP header location ajax call not working PHP header location ajax call not working Jul 10, 2025 pm 01:46 PM

The reason why header('Location:...') in AJAX request is invalid is that the browser will not automatically perform page redirects. Because in the AJAX request, the 302 status code and Location header information returned by the server will be processed as response data, rather than triggering the jump behavior. Solutions are: 1. Return JSON data in PHP and include a jump URL; 2. Check the redirect field in the front-end AJAX callback and jump manually with window.location.href; 3. Ensure that the PHP output is only JSON to avoid parsing failure; 4. To deal with cross-domain problems, you need to set appropriate CORS headers; 5. To prevent cache interference, you can add a timestamp or set cache:f

How do I create a basic route in Yii? How do I create a basic route in Yii? Jul 09, 2025 am 01:15 AM

TocreateabasicrouteinYii,firstsetupacontrollerbyplacingitinthecontrollersdirectorywithpropernamingandclassdefinitionextendingyii\web\Controller.1)Createanactionwithinthecontrollerbydefiningapublicmethodstartingwith"action".2)ConfigureURLstr

How Do Generators Work in PHP? How Do Generators Work in PHP? Jul 11, 2025 am 03:12 AM

AgeneratorinPHPisamemory-efficientwaytoiterateoverlargedatasetsbyyieldingvaluesoneatatimeinsteadofreturningthemallatonce.1.Generatorsusetheyieldkeywordtoproducevaluesondemand,reducingmemoryusage.2.Theyareusefulforhandlingbigloops,readinglargefiles,or

See all articles