For a website development, I try to use Symfony 4 HTTP cache described in documentation.
I created an CacheKernel called in index.php like this :
namespace App;
use Symfony\Bundle\FrameworkBundle\HttpCache\HttpCache;
class CacheKernel extends HttpCache
{
}
// index.php
$kernel = new Kernel($_SERVER['APP_ENV'], (bool) $_SERVER['APP_DEBUG']);
$kernel = new CacheKernel($kernel);
$request = Request::createFromGlobals();
In homepage action:
$response->setPublic();
$response->setMaxAge(3600);
$response->headers->addCacheControlDirective('must-revalidate', true);
return $response;
In profiler, headers are sets :
cache-control "max-age=3600, must-revalidate, public"
But in browser, headers are not same, and I think cache is not stored :
Cache-Control: max-age=0, must-revalidate, private
Have you got some ides to understand why headers are not same and why cache is not working please ?
And how can I make be sure cache is working, is there some logs ?
Thanks a lot for helping
My Answer:
It looks like the cache headers are not being properly passed from your CacheKernel to the browser. One thing you can try is to explicitly set the cache headers in your CacheKernel class.
You can do this by overriding the `getOptions()` method in your CacheKernel class. Here's an example:
php
namespace App;
use Symfony\Bundle\FrameworkBundle\HttpCache\HttpCache;
class CacheKernel extends HttpCache
{
protected function getOptions()
{
return array(
'default_ttl' => 3600,
'private_headers' => array('Authorization', 'Cookie'),
);
}
}
In this example, we are setting the default time-to-live (TTL) to 3600 seconds and specifying that certain headers should be treated as private. This should ensure that the cache headers are properly passed to the browser.
As for checking if the cache is working, you can use browser developer tools to inspect the network requests and responses. Look for the `Cache-Control` header in the response headers to see if the caching directives are being applied.
Additionally, you can enable logging in Symfony to see if the cache is being hit. You can do this by setting the `APP_DEBUG` environment variable to `true` in your `.env` file:
APP_DEBUG=true
This will enable debug mode and you should see cache-related logs in the Symfony profiler.
I hope this helps! Let me know if you have any other questions.
Rate this post
3 of 5 based on 8172 votesComments