The HttpClient component provides a caching feature to avoid repeated HTTP requests for the same content. Internally, it uses the HttpCache class from the HttpKernel component:
1 2 3 4 5 6 7 8 9 10
use Symfony\Component\HttpClient\CachingHttpClient;
use Symfony\Component\HttpClient\HttpClient;
use Symfony\Component\HttpKernel\HttpCache\Store;
$store = new Store('/path/to/cache/storage/');
$client = HttpClient::create();
$client = new CachingHttpClient($client, $store);
// this won't hit the network if the resource is already in the cache
$response = $client->request('GET', 'https://example.com/cacheable-resource');
In Symfony 7.4, we're revamping this feature to get rid of HttpCache, base caching on the Cache component, and make the implementation fully compliant with RFC 9111.
First, define a cache pool whose adapter is tag-aware:
1 2 3 4 5 6 7
# config/packages/framework.yaml
framework:
cache:
pools:
example_cache_pool:
adapter: cache.adapter.redis_tag_aware
tags: true
Then, add the new caching option to your HTTP client to enable caching and
use the given cache pool:
1 2 3 4 5 6 7 8 9 10 11 12 13
# config/packages/framework.yaml
framework:
cache:
pools:
example_cache_pool:
# ...
http_client:
scoped_clients:
example.client:
base_uri: 'https://example.com'
caching:
cache_pool: example_cache_pool
That's all. Requests sent with that client are now cached according to RFC 9111.
The caching option accepts two additional keys:
shared: iftrue(the default value), the client uses a shared cache so cached responses can be reused across users;max_ttl: by default, responses are cached for as long as the TTL specified by the server. When this option is set, server-provided TTLs are capped to this value.
Great feature! Well done! Shouldn't the caching HTTP client be used by default in future Symfony versions (e.g., whenever there is a cache-aware tag registered)?
That looks nice. Sounds like this should make https://jolicode.com/blog/aggressive-caching-with-symfony-http-client easier. But think there is no option yet for aggressive caching / Cache all responses for at least ... time not depend on HTTP headers?
But what I'm curious why the HttpCache of HttpKernel isn't following RFC 9111?
ha ha) we still need to make our own cache for arbitrary caching time) what's the problem with just adding ttl?
Great !! Thanks for this new feature.