# 響應
當應用完成處理一個[請求](http://www.yiichina.com/doc/guide/2.0/runtime-requests)后, 會生成一個yii\web\Response響應對象并發送給終端用戶 響應對象包含的信息有HTTP狀態碼,HTTP頭和主體內容等, 網頁應用開發的最終目的本質上就是根據不同的請求構建這些響應對象。
在大多是情況下主要處理繼承自 yii\web\Response 的?`response`?[應用組件](http://www.yiichina.com/doc/guide/2.0/structure-application-components), 盡管如此,Yii也允許你創建你自己的響應對象并發送給終端用戶,這方面后續會闡述。
在本節,將會描述如何構建響應和發送給終端用戶。
## 狀態碼
構建響應時,最先應做的是標識請求是否成功處理的狀態,可通過設置 yii\web\Response::statusCode 屬性,該屬性使用一個有效的[HTTP 狀態碼](http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html)。例如,為標識處理已被處理成功, 可設置狀態碼為200,如下所示:
~~~
Yii::$app->response->statusCode = 200;
~~~
盡管如此,大多數情況下不需要明確設置狀態碼,因為 yii\web\Response::statusCode 狀態碼默認為200, 如果需要指定請求失敗,可拋出對應的HTTP異常,如下所示:
~~~
throw new \yii\web\NotFoundHttpException;
~~~
當[錯誤處理器](http://www.yiichina.com/doc/guide/2.0/runtime-handling-errors)?捕獲到一個異常,會從異常中提取狀態碼并賦值到響應, 對于上述的 yii\web\NotFoundHttpException 對應HTTP 404狀態碼,以下為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.
如果想拋出的異常不在如上列表中,可創建一個yii\web\HttpException異常,帶上狀態碼拋出,如下:
~~~
throw new \yii\web\HttpException(402);
~~~
## HTTP 頭部
可在?`response`?組件中操控yii\web\Response::headers來發送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()方法調用前新注冊的頭信息并不會發送給用戶。
## 響應主體
大多是響應應有一個主體存放你想要顯示給終端用戶的內容。
如果已有格式化好的主體字符串,可賦值到響應的yii\web\Response::content屬性,例如:
~~~
Yii::$app->response->content = 'hello world!';
~~~
如果在發送給終端用戶之前需要格式化,應設置 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來實現.
上述響應主體可明確地被設置,但是在大多數情況下是通過?[操作](http://www.yiichina.com/doc/guide/2.0/structure-controllers)?方法的返回值隱式地設置,常用場景如下所示:
~~~
public function actionIndex()
{
return $this->render('index');
}
~~~
上述的?`index`?操作返回?`index`?視圖渲染結果,返回值會被?`response`?組件格式化后發送給終端用戶。
因為響應格式默認為yii\web\Response::FORMAT_HTML, 只需要在操作方法中返回一個字符串, 如果想使用其他響應格式,應在返回數據前先設置格式,例如:
~~~
public function actionInfo()
{
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return [
'message' => 'hello world',
'code' => 100,
];
}
~~~
如上所述,觸雷使用默認的?`response`?應用組件,也可創建自己的響應對象并發送給終端用戶,可在操作方法中返回該響應對象,如下所示:
~~~
public function actionInfo()
{
return \Yii::createObject([
'class' => 'yii\web\Response',
'format' => \yii\web\Response::FORMAT_JSON,
'data' => [
'message' => 'hello world',
'code' => 100,
],
]);
}
~~~
> 注意: 如果創建你自己的響應對象,將不能在應用配置中設置?`response`?組件,盡管如此, 可使用?[依賴注入](http://www.yiichina.com/doc/guide/2.0/concept-di-container)?應用通用配置到你新的響應對象。
## 瀏覽器跳轉
瀏覽器跳轉依賴于發送一個`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()`?方法的結果,如前所述,操作的方法返回的響應對象會被當總響應發送給終端用戶。
除了操作方法外,可直接調用yii\web\Response::redirect() 再調用 yii\web\Response::send() 方法來確保沒有其他內容追加到響應中。
~~~
\Yii::$app->response->redirect('http://example.com/new', 301)->send();
~~~
> 補充: yii\web\Response::redirect() 方法默認會設置響應狀態碼為302,該狀態碼會告訴瀏覽器請求的資源?*臨時*?放在另一個URI地址上,可傳遞一個301狀態碼告知瀏覽器請求的資源已經?*永久*?重定向到新的URId地址。
如果當前請求為AJAX 請求,發送一個?`Location`?頭不會自動使瀏覽器跳轉,為解決這個問題, yii\web\Response::redirect() 方法設置一個值為要跳轉的URL的`X-Redirect`?頭, 在客戶端可編寫JavaScript 代碼讀取該頭部值然后讓瀏覽器跳轉對應的URL。
> 補充: Yii 配備了一個`yii.js`?JavaScript 文件提供常用JavaScript功能,包括基于`X-Redirect`頭的瀏覽器跳轉, 因此,如果你使用該JavaScript 文件(通過yii\web\YiiAsset 資源包注冊),就不需要編寫AJAX跳轉的代碼。
## 發送文件
和瀏覽器跳轉類似,文件發送是另一個依賴指定HTTP頭的功能,Yii提供方法集合來支持各種文件發送需求,它們對HTTP頭都有內置的支持。
* yii\web\Response::sendFile(): 發送一個已存在的文件到客戶端
* yii\web\Response::sendContentAsFile(): 發送一個文本字符串作為文件到客戶端
* yii\web\Response::sendStreamAsFile(): 發送一個已存在的文件流作為文件到客戶端
這些方法都將響應對象作為返回值,如果要發送的文件非常大,應考慮使用 yii\web\Response::sendStreamAsFile() 因為它更節約內存,以下示例顯示在控制器操作中如何發送文件:
~~~
public function actionDownload()
{
return \Yii::$app->response->sendFile('path/to/file.txt');
}
~~~
如果不是在操作方法中調用文件發送方法,在后面還應調用 yii\web\Response::send() 沒有其他內容追加到響應中。
~~~
\Yii::$app->response->sendFile('path/to/file.txt')->send();
~~~
一些瀏覽器提供特殊的名為*X-Sendfile*的文件發送功能,原理為將請求跳轉到服務器上的文件, Web應用可在服務器發送文件前結束,為使用該功能,可調用yii\web\Response::xSendFile(), 如下簡要列出一些常用Web服務器如何啟用`X-Sendfile`?功能:
* Apache:?[X-Sendfile](http://tn123.org/mod_xsendfile)
* Lighttpd v1.4:?[X-LIGHTTPD-send-file](http://redmine.lighttpd.net/projects/lighttpd/wiki/X-LIGHTTPD-send-file)
* Lighttpd v1.5:?[X-Sendfile](http://redmine.lighttpd.net/projects/lighttpd/wiki/X-LIGHTTPD-send-file)
* Nginx:?[X-Accel-Redirect](http://wiki.nginx.org/XSendfile)
* Cherokee:?[X-Sendfile and X-Accel-Redirect](http://www.cherokee-project.com/doc/other_goodies.html#x-sendfile)
## 發送響應
在yii\web\Response::send() 方法調用前響應中的內容不會發送給用戶,該方法默認在yii\base\Application::run() 結尾自動調用,盡管如此,可以明確調用該方法強制立即發送響應。
yii\web\Response::send() 方法使用以下步驟來發送響應:
1. 觸發 yii\web\Response::EVENT_BEFORE_SEND 事件.
2. 調用 yii\web\Response::prepare() 來格式化 yii\web\Response::data 為 yii\web\Response::content.
3. 觸發 yii\web\Response::EVENT_AFTER_PREPARE 事件.
4. 調用 yii\web\Response::sendHeaders() 來發送注冊的HTTP頭
5. 調用 yii\web\Response::sendContent() 來發送響應主體內容
6. 觸發 yii\web\Response::EVENT_AFTER_SEND 事件.
一旦yii\web\Response::send() 方法被執行后,其他地方調用該方法會被忽略, 這意味著一旦響應發出后,就不能再追加其他內容。
如你所見yii\web\Response::send() 觸發了幾個實用的事件,通過響應這些事件可調整或包裝響應。
- 介紹(Introduction)
- 關于 Yii(About Yii)
- 從 Yii 1.1 升級(Upgrading from Version 1.1)
- 入門(Getting Started)
- 安裝 Yii(Installing Yii)
- 運行應用(Running Applications)
- 第一次問候(Saying Hello)
- 使用 Forms(Working with Forms)
- 玩轉 Databases(Working with Databases)
- 用 Gii 生成代碼(Generating Code with Gii)
- 更上一層樓(Looking Ahead)
- 應用結構(Application Structure)
- 結構概述(Overview)
- 入口腳本(Entry Scripts)
- 應用(Applications)
- 應用組件(Application Components)
- 控制器(Controllers)
- 模型(Models)
- 視圖(Views)
- 模塊(Modules)
- 過濾器(Filters)
- 小部件(Widgets)
- 前端資源(Assets)
- 擴展(Extensions)
- 請求處理(Handling Requests)
- 運行概述(Overview)
- 引導(Bootstrapping)
- 路由引導與創建 URL(Routing and URL Creation)
- 請求(Requests)
- 響應(Responses)
- Sessions and Cookies
- 錯誤處理(Handling Errors)
- 日志(Logging)
- 關鍵概念(Key Concepts)
- 組件(Components)
- 屬性(Properties)
- 事件(Events)
- 行為(Behaviors)
- 配置(Configurations)
- 別名(Aliases)
- 類自動加載(Class Autoloading)
- 服務定位器(Service Locator)
- 依賴注入容器(Dependency Injection Container)
- 配合數據庫工作(Working with Databases)
- 數據庫訪問(Data Access Objects): 數據庫連接、基本查詢、事務和模式操作
- 查詢生成器(Query Builder): 使用簡單抽象層查詢數據庫
- 活動記錄(Active Record): 活動記錄對象關系映射(ORM),檢索和操作記錄、定義關聯關系
- 數據庫遷移(Migrations): 在團體開發中對你的數據庫使用版本控制
- Sphinx
- Redis
- MongoDB
- ElasticSearch
- 接收用戶數據(Getting Data from Users)
- 創建表單(Creating Forms)
- 輸入驗證(Validating Input)
- 文件上傳(Uploading Files)
- 收集列表輸入(Collecting Tabular Input)
- 多模型同時輸入(Getting Data for Multiple Models)
- 顯示數據(Displaying Data)
- 格式化輸出數據(Data Formatting)
- 分頁(Pagination)
- 排序(Sorting)
- 數據提供器(Data Providers)
- 數據小部件(Data Widgets)
- 操作客戶端腳本(Working with Client Scripts)
- 主題(Theming)
- 安全(Security)
- 認證(Authentication)
- 授權(Authorization)
- 處理密碼(Working with Passwords)
- 客戶端認證(Auth Clients)
- 安全領域的最佳實踐(Best Practices)
- 緩存(Caching)
- 概述(Overview)
- 數據緩存(Data Caching)
- 片段緩存(Fragment Caching)
- 分頁緩存(Page Caching)
- HTTP 緩存(HTTP Caching)
- RESTful Web 服務
- 快速入門(Quick Start)
- 資源(Resources)
- 控制器(Controllers)
- 路由(Routing)
- 格式化響應(Response Formatting)
- 授權驗證(Authentication)
- 速率限制(Rate Limiting)
- 版本化(Versioning)
- 錯誤處理(Error Handling)
- 開發工具(Development Tools)
- 調試工具欄和調試器(Debug Toolbar and Debugger)
- 使用 Gii 生成代碼(Generating Code using Gii)
- TBD 生成 API 文檔(Generating API Documentation)
- 測試(Testing)
- 概述(Overview)
- 搭建測試環境(Testing environment setup)
- 單元測試(Unit Tests)
- 功能測試(Functional Tests)
- 驗收測試(Acceptance Tests)
- 測試夾具(Fixtures)
- 高級專題(Special Topics)
- 高級應用模版(Advanced Project Template)
- 從頭構建自定義模版(Building Application from Scratch)
- 控制臺命令(Console Commands)
- 核心驗證器(Core Validators)
- 國際化(Internationalization)
- 收發郵件(Mailing)
- 性能優化(Performance Tuning)
- 共享主機環境(Shared Hosting Environment)
- 模板引擎(Template Engines)
- 集成第三方代碼(Working with Third-Party Code)
- 小部件(Widgets)
- Bootstrap 小部件(Bootstrap Widgets)
- jQuery UI 小部件(jQuery UI Widgets)
- 助手類(Helpers)
- 助手一覽(Overview)
- Array 助手(ArrayHelper)
- Html 助手(Html)
- Url 助手(Url)