Slim 3使用一个可选的独立PHP 组件slimphp/Slim-HttpCache 作为HTTP 缓存.可以使用这个组件创建或者返回一个响应包含 Cache
,Expires
,ETag
和 Last-Modified
HTTP头去控制什么时候和多长时间应用输出的是保留在客户端那边的缓存.
安装
进入命令行,在你的项目的根目录底下执行下面的代码:
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
HTTP 头,这个方法接收PSR 7响应对象并且克隆一个PSR7响应对象带着新的HTTP 头:
$app->get('/foo', function ($req, $res, $args) {
$resWithEtag = $this->cache->withEtag($res, 'abc');
return $resWithEtag;
});
Expires
使用服务提供的方法 withExpires()
创建一个响应对象会包含 Expires
HTTP 头,这个方法接收PSR 7响应对象并且克隆一个PSR7响应对象带着新的HTTP 头:
$app->get('/bar',function ($req, $res, $args) {
$resWithExpires = $this->cache->withExpires($res, time() + 3600);
return $resWithExpires;
});
Last-Modified
使用服务提供的方法 withLastModified()
创建一个响应对象会包含 Last-Modified
HTTP 头,这个方法接收PSR 7响应对象并且克隆一个PSR7响应对象带着新的HTTP 头:
//Example route with LastModified
$app->get('/foobar',function ($req, $res, $args) {
$resWithLastMod = $this->cache->withLastModified($res, time() - 3600);
return $resWithLastMod;
});
文档翻译的并不是很专业,仅供个人学习作用,建议看官方文档。
如有兴趣,请看下一篇 SLIM 3 文档(十四)-CSRF 保护