亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

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;

// 返回所有參數
$params = $request->bodyParams;

// 返回參數 "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;

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

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

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

1.狀態(tài)碼

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

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

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

throw new \yii\web\NotFoundHttpException;

當錯誤處理器 捕獲到一個異常,會從異常中提取狀態(tài)碼并賦值到響應, 對于上述的 yii\web\NotFoundHttpException 對應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');

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

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

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

3.響應主體

大多是響應應有一個主體存放你想要顯示給終端用戶的內容。

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

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

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

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

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

  • yii\web\Response::FORMAT_HTML: 通過 yii\web\HtmlResponseFormatter 來實現.
  • yii\web\Response::FORMAT_XML: 通過 yii\web\XmlResponseFormatter來實現.
  • yii\web\Response::FORMAT_JSON: 通過 yii\web\JsonResponseFormatter來實現.
  • yii\web\Response::FORMAT_JSONP: 通過 yii\web\JsonResponseFormatter來實現.

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

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

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

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

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

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

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

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

4.瀏覽器跳轉

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

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

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

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

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

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

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

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

5.發(fā)送文件

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

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

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

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

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

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

一些瀏覽器提供特殊的名為X-Sendfile的文件發(fā)送功能,原理為將請求跳轉到服務器上的文件, Web應用可在服務器發(fā)送文件前結束,為使用該功能,可調用yii\web\Response::xSendFile(), 如下簡要列出一些常用Web服務器如何啟用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ā)送響應

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

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

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

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

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

您可能感興趣的文章:

  • PHP的Yii框架中行為的定義與綁定方法講解
  • 詳解在PHP的Yii框架中使用行為Behaviors的方法
  • 深入講解PHP的Yii框架中的屬性(Property)
  • PHP的Yii框架中使用數據庫的配置和SQL操作實例教程
  • 實例講解如何在PHP的Yii框架中進行錯誤和異常處理
  • 解析PHP的Yii框架中cookie和session功能的相關操作
  • 簡要剖析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)

How to use PHP to build social sharing functions PHP sharing interface integration practice How to use PHP to build social sharing functions PHP sharing interface integration practice Jul 25, 2025 pm 08:51 PM

The core method of building social sharing functions in PHP is to dynamically generate sharing links that meet the requirements of each platform. 1. First get the current page or specified URL and article information; 2. Use urlencode to encode the parameters; 3. Splice and generate sharing links according to the protocols of each platform; 4. Display links on the front end for users to click and share; 5. Dynamically generate OG tags on the page to optimize sharing content display; 6. Be sure to escape user input to prevent XSS attacks. This method does not require complex authentication, has low maintenance costs, and is suitable for most content sharing needs.

How to use PHP combined with AI to achieve text error correction PHP syntax detection and optimization How to use PHP combined with AI to achieve text error correction PHP syntax detection and optimization Jul 25, 2025 pm 08:57 PM

To realize text error correction and syntax optimization with AI, you need to follow the following steps: 1. Select a suitable AI model or API, such as Baidu, Tencent API or open source NLP library; 2. Call the API through PHP's curl or Guzzle and process the return results; 3. Display error correction information in the application and allow users to choose whether to adopt it; 4. Use php-l and PHP_CodeSniffer for syntax detection and code optimization; 5. Continuously collect feedback and update the model or rules to improve the effect. When choosing AIAPI, focus on evaluating accuracy, response speed, price and support for PHP. Code optimization should follow PSR specifications, use cache reasonably, avoid circular queries, review code regularly, and use X

PHP creates a blog comment system to monetize PHP comment review and anti-brush strategy PHP creates a blog comment system to monetize PHP comment review and anti-brush strategy Jul 25, 2025 pm 08:27 PM

1. Maximizing the commercial value of the comment system requires combining native advertising precise delivery, user paid value-added services (such as uploading pictures, top-up comments), influence incentive mechanism based on comment quality, and compliance anonymous data insight monetization; 2. The audit strategy should adopt a combination of pre-audit dynamic keyword filtering and user reporting mechanisms, supplemented by comment quality rating to achieve content hierarchical exposure; 3. Anti-brushing requires the construction of multi-layer defense: reCAPTCHAv3 sensorless verification, Honeypot honeypot field recognition robot, IP and timestamp frequency limit prevents watering, and content pattern recognition marks suspicious comments, and continuously iterate to deal with attacks.

PHP calls AI intelligent voice assistant PHP voice interaction system construction PHP calls AI intelligent voice assistant PHP voice interaction system construction Jul 25, 2025 pm 08:45 PM

User voice input is captured and sent to the PHP backend through the MediaRecorder API of the front-end JavaScript; 2. PHP saves the audio as a temporary file and calls STTAPI (such as Google or Baidu voice recognition) to convert it into text; 3. PHP sends the text to an AI service (such as OpenAIGPT) to obtain intelligent reply; 4. PHP then calls TTSAPI (such as Baidu or Google voice synthesis) to convert the reply to a voice file; 5. PHP streams the voice file back to the front-end to play, completing interaction. The entire process is dominated by PHP to ensure seamless connection between all links.

How to use PHP to combine AI to generate image. PHP automatically generates art works How to use PHP to combine AI to generate image. PHP automatically generates art works Jul 25, 2025 pm 07:21 PM

PHP does not directly perform AI image processing, but integrates through APIs, because it is good at web development rather than computing-intensive tasks. API integration can achieve professional division of labor, reduce costs, and improve efficiency; 2. Integrating key technologies include using Guzzle or cURL to send HTTP requests, JSON data encoding and decoding, API key security authentication, asynchronous queue processing time-consuming tasks, robust error handling and retry mechanism, image storage and display; 3. Common challenges include API cost out of control, uncontrollable generation results, poor user experience, security risks and difficult data management. The response strategies are setting user quotas and caches, providing propt guidance and multi-picture selection, asynchronous notifications and progress prompts, key environment variable storage and content audit, and cloud storage.

PHP realizes commodity inventory management and monetization PHP inventory synchronization and alarm mechanism PHP realizes commodity inventory management and monetization PHP inventory synchronization and alarm mechanism Jul 25, 2025 pm 08:30 PM

PHP ensures inventory deduction atomicity through database transactions and FORUPDATE row locks to prevent high concurrent overselling; 2. Multi-platform inventory consistency depends on centralized management and event-driven synchronization, combining API/Webhook notifications and message queues to ensure reliable data transmission; 3. The alarm mechanism should set low inventory, zero/negative inventory, unsalable sales, replenishment cycles and abnormal fluctuations strategies in different scenarios, and select DingTalk, SMS or Email Responsible Persons according to the urgency, and the alarm information must be complete and clear to achieve business adaptation and rapid response.

Beyond the LAMP Stack: PHP's Role in Modern Enterprise Architecture Beyond the LAMP Stack: PHP's Role in Modern Enterprise Architecture Jul 27, 2025 am 04:31 AM

PHPisstillrelevantinmodernenterpriseenvironments.1.ModernPHP(7.xand8.x)offersperformancegains,stricttyping,JITcompilation,andmodernsyntax,makingitsuitableforlarge-scaleapplications.2.PHPintegrateseffectivelyinhybridarchitectures,servingasanAPIgateway

How to build a PHP Nginx environment with MacOS to configure the combination of Nginx and PHP services How to build a PHP Nginx environment with MacOS to configure the combination of Nginx and PHP services Jul 25, 2025 pm 08:24 PM

The core role of Homebrew in the construction of Mac environment is to simplify software installation and management. 1. Homebrew automatically handles dependencies and encapsulates complex compilation and installation processes into simple commands; 2. Provides a unified software package ecosystem to ensure the standardization of software installation location and configuration; 3. Integrates service management functions, and can easily start and stop services through brewservices; 4. Convenient software upgrade and maintenance, and improves system security and functionality.

See all articles