Caching
Sometimes you may wish to cache the responses that come back from the API integrations you are integrating. Saloon has a first-party package plugin that you can install to enable this functionality.
Currently the caching plugin only supports explicit caching, where you define when a request should be cached. There will be an update in the future that introduces caching based on the Cache-Control headers.
Installation
Firstly, install the Saloon Cache Plugin from Composer into your project.
Configuration
After you have installed the plugin, add the AlwaysCacheResponses trait to your request or connector. After you have added the trait, you will need to define the cache driver and the cache TTL.
If you add the caching plugin to your connector, it will cache every single request that the connector uses.
Cache Drivers
There are three available cache drivers that you can use. The cache driver defines how the cache file will be stored and retrieved by the cache plugin.
FlysystemDriver
Allows you to define a Flysystem storage driver that will be used to store the cache files. This allows you to store the cache files in many places like Amazon S3. Learn more about Flysystem
LaravelCacheDriver
Allows you to define a Laravel Cache store like database/redis. This should only be used if you are using Saloon in Laravel.
SimpleCacheDriver (PSR-16 Compatible)
Allows you to use any PSR-16 compatible cache.
Response
Saloon will respond with a Saloon response (or your custom response if defined) when retrieving a cached response. To check if a response has been cached, you can use the isCached()
method.
Custom Cache Keys
By default, the cache key will be built up from the full URL of the request, the class name and the headers of the request. The plugin will create a SHA-256 hash based on these three items. If you would like to have your own custom cache key, like using the UUID of a user, then you can extend the cacheKey
method.
Disable Caching
Sometimes you may wish to disable the caching on a per-request basis for debugging or to bypass caching. You can do this by using the disableCaching
method on the request.
Invalidating Cache
You may want to make a request and purge the existing cache before making the request. You can use the invalidateCache
method on the request before sending the request and Saloon will delete any existing cache for that request.
Source Code
Last updated