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 SF versions (e.g., whenever there is a cache-aware tag registered)?