HTTP Caching

Slim 3 uses the optional standalone slimphp/Slim-HttpCache PHP componentfor HTTP caching. You can use this component to create and return responses thatcontain Cache, Expires, ETag, and Last-Modified headers that controlwhen and how long application output is retained by client-side caches. You may have to set your php.ini setting “session.cache_limiter” to an empty string in order to get this working without interferences.

Installation

Execute this bash command from your project’s root directory:

  1. composer require slim/http-cache

Usage

The slimphp/Slim-HttpCache component contains a service provider and an applicationmiddleware. You should add both to your application like this:

  1. // Register service provider with the container
  2. $container = new \Slim\Container;
  3. $container['cache'] = function () {
  4. return new \Slim\HttpCache\CacheProvider();
  5. };
  6. // Add middleware to the application
  7. $app = new \Slim\App($container);
  8. $app->add(new \Slim\HttpCache\Cache('public', 86400));
  9. // Create your application routes...
  10. // Run application
  11. $app->run();

ETag

Use the service provider’s withEtag() method to create a Response objectwith the desired ETag header. This method accepts a PSR7 response object,and it returns a cloned PSR7 response with the new HTTP header.

  1. $app->get('/foo', function ($req, $res, $args) {
  2. $resWithEtag = $this->cache->withEtag($res, 'abc');
  3. return $resWithEtag;
  4. });

Expires

Use the service provider’s withExpires() method to create a Response objectwith the desired Expires header. This method accepts a PSR7 response object,and it returns a cloned PSR7 response with the new HTTP header.

  1. $app->get('/bar',function ($req, $res, $args) {
  2. $resWithExpires = $this->cache->withExpires($res, time() + 3600);
  3. return $resWithExpires;
  4. });

Last-Modified

Use the service provider’s withLastModified() method to create a Response objectwith the desired Last-Modified header. This method accepts a PSR7 response object,and it returns a cloned PSR7 response with the new HTTP header.

  1. //Example route with LastModified
  2. $app->get('/foobar',function ($req, $res, $args) {
  3. $resWithLastMod = $this->cache->withLastModified($res, time() - 3600);
  4. return $resWithLastMod;
  5. });