# 返回響應(Returning Responses)
[Phalcon\\Http\\Response](http://docs.iphalcon.cn/api/Phalcon_Http_Response.html)是Phalcon中用來處理HTTP響應返回的組件。 HTTP響應通常是由響應頭和響應體組成的。下面是一些基本用法:
~~~
<?php
use Phalcon\Http\Response;
// 獲取一個響應實例
$response = new Response();
// 設置HTTP狀態碼
$response->setStatusCode(404, "Not Found");
// 設置響應內容
$response->setContent("Sorry, the page doesn't exist");
// 返回響應到客戶端
$response->send();
~~~
If you are using the full MVC stack there is no need to create responses manually. However, if you need to return a response directly from a controller’s action follow this example:
~~~
<?php
use Phalcon\Http\Response;
use Phalcon\Mvc\Controller;
class FeedController extends Controller
{
public function getAction()
{
// Getting a response instance
$response = new Response();
$feed = // ... Load here the feed
// Set the content of the response
$response->setContent(
$feed->asString()
);
// Return the response
return $response;
}
}
~~~
## 使用頭部信息(Working with Headers)
在HTTP響應返回中,響應頭(Headers)是非常重要的組成部分. 它包含了一些非常有用的信息,比如HTTP狀態碼,響應類型等等.
你可以使用如下方式來設置頭信息:
~~~
<?php
// Setting a header by its name
$response->setHeader("Content-Type", "application/pdf");
$response->setHeader("Content-Disposition", 'attachment; filename="downloaded.pdf"');
// Setting a raw header
$response->setRawHeader("HTTP/1.1 200 OK");
~~~
A[Phalcon\\Http\\Response\\Headers](http://docs.iphalcon.cn/api/Phalcon_Http_Response_Headers.html)bag internally manages headers. This class retrieves the headers before sending it to client:
~~~
<?php
// Get the headers bag
$headers = $response->getHeaders();
// Get a header by its name
$contentType = $headers->get("Content-Type");
~~~
## 重定向(Making Redirections)
可以通過[Phalcon\\Http\\Response](http://docs.iphalcon.cn/api/Phalcon_Http_Response.html)來執行HTTP重定向:
~~~
<?php
// Redirect to the default URI
$response->redirect();
// Redirect to the local base URI
$response->redirect("posts/index");
// Redirect to an external URL
$response->redirect("http://en.wikipedia.org", true);
// Redirect specifying the HTTP status code
$response->redirect("http://www.example.com/new-location", true, 301);
~~~
All internal URIs are generated using the ‘url’ service (by default[Phalcon\\Mvc\\Url](http://docs.iphalcon.cn/reference/url.html)). This example demonstrates how you can redirect using a route you have defined in your application:
所有內部 URIs 都是通過 ‘url’ 來生成的( 默認是[Phalcon\\Mvc\\Url](http://docs.iphalcon.cn/reference/url.html))。下面的例子演示如何通過一個應用內預先定義好的路由來重定向。
~~~
<?php
// Redirect based on a named route
return $response->redirect(
[
"for" => "index-lang",
"lang" => "jp",
"controller" => "index",
]
);
~~~
Note that a redirection doesn’t disable the view component, so if there is a view associated with the current action it will be executed anyway. You can disable the view from a controller by executing`$this->view->disable()`;
值得注意的是重定向并不禁用view組件,所以如果當前的action存在一個關聯的view的話,將會繼續執行它。在控制器中可以通過`$this->view->disable()`來禁用view。
## HTTP 緩存(HTTP Cache)
One of the easiest ways to improve the performance in your applications and reduce the traffic is using HTTP Cache. Most modern browsers support HTTP caching and is one of the reasons why many websites are currently fast.
HTTP Cache can be altered in the following header values sent by the application when serving a page for the first time:
* *Expires:*With this header the application can set a date in the future or the past telling the browser when the page must expire.
* *Cache-Control:*This header allows to specify how much time a page should be considered fresh in the browser.
* *Last-Modified:*This header tells the browser which was the last time the site was updated avoiding page re-loads
* *ETag:*An etag is a unique identifier that must be created including the modification timestamp of the current page
### 設置過期時間(Setting an Expiration Time)
The expiration date is one of the easiest and most effective ways to cache a page in the client (browser). Starting from the current date we add the amount of time the page will be stored in the browser cache. Until this date expires no new content will be requested from the server:
~~~
<?php
$expiryDate = new DateTime();
$expiryDate->modify("+2 months");
$response->setExpires($expiryDate);
~~~
The Response component automatically shows the date in GMT timezone as expected in an Expires header.
If we set this value to a date in the past the browser will always refresh the requested page:
~~~
<?php
$expiryDate = new DateTime();
$expiryDate->modify("-10 minutes");
$response->setExpires($expiryDate);
~~~
Browsers rely on the client’s clock to assess if this date has passed or not. The client clock can be modified to make pages expire and this may represent a limitation for this cache mechanism.
### Cache-Control
This header provides a safer way to cache the pages served. We simply must specify a time in seconds telling the browser how long it must keep the page in its cache:
~~~
<?php
// Starting from now, cache the page for one day
$response->setHeader("Cache-Control", "max-age=86400");
~~~
The opposite effect (avoid page caching) is achieved in this way:
~~~
<?php
// Never cache the served page
$response->setHeader("Cache-Control", "private, max-age=0, must-revalidate");
~~~
### E-Tag
An “entity-tag” or “E-tag” is a unique identifier that helps the browser realize if the page has changed or not between two requests. The identifier must be calculated taking into account that this must change if the previously served content has changed:
~~~
<?php
// Calculate the E-Tag based on the modification time of the latest news
$mostRecentDate = News::maximum(
[
"column" => "created_at"
]
);
$eTag = md5($mostRecentDate);
// Send an E-Tag header
$response->setHeader("E-Tag", $eTag);
~~~
- 簡介
- 安裝
- 安裝(installlation)
- XAMPP下的安裝
- WAMP下安裝
- Nginx安裝說明
- Apache安裝說明
- Cherokee 安裝說明
- 使用 PHP 內置 web 服務器
- Phalcon 開發工具
- Linux 系統下使用 Phalcon 開發工具
- Mac OS X 系統下使用 Phalcon 開發工具
- Windows 系統下使用 Phalcon 開發工具
- 教程
- 教程 1:讓我們通過例子來學習
- 教程 2:INVO簡介
- 教程 3: 保護INVO
- 教程4: 使用CRUD
- 教程5: 定制INVO
- 教程 6: V?kuró
- 教程 7:創建簡單的 REST API
- 組件
- 依賴注入與服務定位器
- MVC架構
- 使用控制器
- 使用模型
- 模型關系
- 事件與事件管理器
- Behaviors
- 模型元數據
- 事務管理
- 驗證數據完整性
- Workingwith Models
- Phalcon查詢語言
- 緩存對象關系映射
- 對象文檔映射 ODM
- 使用視圖
- 視圖助手
- 資源文件管理
- Volt 模版引擎
- MVC 應用
- 路由
- 調度控制器
- Micro Applications
- 使用命名空間
- 事件管理器
- Request Environmen
- 返回響應
- Cookie 管理
- 生成 URL 和 路徑
- 閃存消息
- 使用 Session 存儲數據
- 過濾與清理
- 上下文編碼
- 驗證Validation
- 表單_Forms
- 讀取配置
- 分頁 Pagination
- 使用緩存提高性能
- 安全
- 加密與解密 Encryption/Decryption
- 訪問控制列表
- 多語言支持
- 類加載器 Class Autoloader
- 日志記錄_Logging
- 注釋解析器 Annotations Parser
- 命令行應用 Command Line Applications
- Images
- 隊列 Queueing
- 數據庫抽象層
- 國際化
- 數據庫遷移
- 調試應用程序
- 單元測試
- 進階技巧與延伸閱讀
- 提高性能:下一步該做什么?
- Dependency Injection Explained
- Understanding How Phalcon Applications Work
- Api
- Abstract class Phalcon\Acl