Slim 3 는 HTTP 캐싱을 위해 독립적인 slimphp/Slim-HttpCache PHP 컴포넌트를 사용할 수 있다.
이 컴포넌트를 사용하면, 어플리케이션 출력이 클라이언트 측 캐시에 얼마나 유지될 것인지 제어하는 Cache, Expires, ETag, Last-Modified 헤더들을 포함하는 응답을 생성하고 반환할 수 있다.
설치
프로젝트 루트 디렉토리에서 다음 bash 명령을 실행한다.
$ composer require slim/http-cache | cs |
사용
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(); | cs |
ETag
원하는 ETag 헤더로 Response 객체를 생성하기 위해 서비스 제공자의 withEtag() 메소드를 사용할 수 있다.
이 메소드는 PSR-7 응답 객체를 받고, 새로운 HTTP 헤더로 복제된 PSR7 응답을 반환한다.
$app->get('/foo', function ($req, $res, $args) { $resWithEtag = $this->cache->withEtag($res, 'abc'); return $resWithEtag; }); | cs |
Expires
원하는 Expires 헤더로 Response 객체를 생성하기 위해 서비스 제공자의 withExpires() 메소드를 사용할 수 있다.
이 메소드는 PSR-7 응답 객체를 받고, 새로운 HTTP 헤더로 복제된 PSR7 응답을 반환한다.
$app->get('/bar',function ($req, $res, $args) { $resWithExpires = $this->cache->withExpires($res, time() + 3600); return $resWithExpires; }); | cs |
Last-Modified
원하는 Last-Modified 헤더로 Response 객체를 생성하기 위해 서비스 제공자의 withLastModified() 메소드를 사용할 수 있다.
이 메소드는 PSR-7 응답 객체를 받고, 새로운 HTTP 헤더로 복제된 PSR7 응답을 반환한다.
//Example route with LastModified $app->get('/foobar',function ($req, $res, $args) { $resWithLastMod = $this->cache->withLastModified($res, time() - 3600); return $resWithLastMod; }); | cs |
WRITTEN BY
- 손가락귀신
정신 못차리면, 벌 받는다.
,