# HTTP 緩存
[Edit This Page](https://github.com/slimphp/Slim-Website/tree/gh-pages/docs/features/caching.md)
Slim 3 使用 [slimphp/Slim-HttpCache](https://github.com/slimphp/Slim-HttpCache) 這款獨立的 PHP 組件作為可選的 HTTP 緩存工具。可以使用這個組件創建并返回包含 `Cache`, `Expires`, `ETag`, 和 `Last-Modified` 頭的 HTTP 響應,以控制何時以及如何使用客戶端緩存保留應用程序的輸出。
## 安裝
在你的項目的根目錄下執行這個bash命令:
```
composer require slim/http-cache
```
## 用法
這個 `slimphp/Slim-HttpCache` 組件包含一個服務提供程序和一個應用程序中間件。你必須在你的應用程序中添加這兩個玩意,像這樣:
```
// Register service provider with the container
$container = new \Slim\Container;
$container['cache'] = function () {
return new \Slim\HttpCache\CacheProvider();
};
// Add middleware to the application
$app = new \Slim\App($container);
$app->add(new \Slim\HttpCache\Cache('public', 86400));
// Create your application routes...
// Run application
$app->run();
```
## ETag
使用服務提供程序的 `withEtag()` 方法創建一個帶有指定 `ETag` 頭的響應對象。這個方法接收一個 PSR7 響應對象,而且它返回一個帶有新 HTTP 頭的 PSR7 響應的拷貝。
```
$app->get('/foo', function ($req, $res, $args) {
$resWithEtag = $this->cache->withEtag($res, 'abc');
return $resWithEtag;
});
```
## Expires
使用服務提供程序的 `withExpires()` 方法創建一個帶有指定 `Expires` 頭的響應對象。這個方法接收一個 PSR7 響應對象,而且它返回一個帶有新的 HTTP 頭的 PSR7 響應的拷貝。
```
$app->get('/bar',function ($req, $res, $args) {
$resWithExpires = $this->cache->withExpires($res, time() + 3600);
return $resWithExpires;
});
```
## Last-Modified
使用服務提供程序的`withLastModified()` 方法創建一個帶有指定 `Last-Modified` 頭的響應對象。這個方法接收一個 PSR7 響應對象,而且它返回一個帶有新 HTTP 頭的 PSR7 響應的拷貝。
```
//Example route with LastModified
$app->get('/foobar',function ($req, $res, $args) {
$resWithLastMod = $this->cache->withLastModified($res, time() - 3600);
return $resWithLastMod;
});
```