Skip to content

Instantly share code, notes, and snippets.

@rkueny
Created October 1, 2019 19:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rkueny/55ed9b34af1f8f00a4282e9e036e5a8b to your computer and use it in GitHub Desktop.
Save rkueny/55ed9b34af1f8f00a4282e9e036e5a8b to your computer and use it in GitHub Desktop.
<?php
use Symfony\Component\HttpFoundation\Response;
// ...
public function index()
{
// somehow create a Response object, like by rendering a template
$response = $this->render('blog/index.html.twig', []);
// cache for 3600 seconds
$response->setSharedMaxAge(3600);
/*
$response->setCache([
'etag' => $etag,
'last_modified' => $date,
'max_age' => 10,
's_maxage' => 10,
'public' => true,
// 'private' => true,
]);
*/
// (optional) set a custom Cache-Control directive
$response->headers->addCacheControlDirective('must-revalidate', true);
return $response;
}
<?php
namespace App;
use Symfony\Bundle\FrameworkBundle\HttpCache\HttpCache;
class CacheKernel extends HttpCache
{
protected function getOptions()
{
return [
'default_ttl' => 0,
// more infos on https://github.com/symfony/symfony/blob/4.3/src/Symfony/Component/HttpKernel/HttpCache/HttpCache.php
];
}
}
<?php
+ use App\CacheKernel;
use App\Kernel;
// ...
$kernel = new Kernel($_SERVER['APP_ENV'], (bool) $_SERVER['APP_DEBUG']);
+ // Wrap the default Kernel with the CacheKernel one in 'prod' environment
+ if ('prod' === $kernel->getEnvironment()) {
+ $kernel = new CacheKernel($kernel);
+ }
$request = Request::createFromGlobals();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment