2

What is HTTP Cache for? How do I use it in Slim 3?

But I am not quite sure how this is done in Slim 3:

use Slim\Http\Request;
use Slim\Http\Response;

require_once __DIR__ . '/../vendor/autoload.php';

// Register service provider with the container
$container = new \Slim\Container;
$container['cache'] = function () {
    return new \Slim\HttpCache\CacheProvider();
};

$app = new \Slim\App($container);

// Add middleware to the application.
$app->add(new \Slim\HttpCache\Cache('cache', 86400));

// Routes:
$app->get('/', function (Request $request, Response $response, array $args) {
    $response->getBody()->write('Hello, World!');

    return $response->withHeader('Content-type', 'application/json');
});

$app->get('/foo', function ($req, $res, $args) {
    $resWithEtag = $this->cache
    ->withEtag($res, 'abc')
    // ->withExpires($res, time() + 60)
    ;

    return $resWithEtag;
});

$app->run();

Any ideas?

Run
  • 54,938
  • 169
  • 450
  • 748

1 Answers1

3

\Slim\HttpCache\Cache() is HTTP Cache for client-side (browser) caching

It expects up to 3 Parameters:

 * @param string $type           The cache type: "public" or "private"
 * @param int    $maxAge         The maximum age of client-side cache
 * @param bool   $mustRevalidate must-revalidate

and generates corresponding HTTP-response headers.

It has nothing with server-side caching to do.

Gennadiy Litvinyuk
  • 1,536
  • 12
  • 21
  • is HTTP Cache different from what I am looking for? – Run Dec 21 '15 at 09:49
  • 1
    I think this is very different. Browser caching works in your browser. To cache something, you have visit a webpage once, then, is you visit this page again th browser will not send a new request, if the cache is still valid. It works at best for static files like css, javascript and images. Server-side caching is completly different. You cache to save time on expensive database-requests or calculations. For the 1st visitor it will be slow, for other - could be quicker... you should also understand when to cache or diffiretiate caches... – Gennadiy Litvinyuk Dec 21 '15 at 10:36