企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# 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; }); ```