Caching
Last updated
Last updated
There are scenarios where you may want to cache a response from an API, like retrieving a static list or retrieving data that you know won't change for a specified amount of time. Caching can be incredibly powerful and can speed up an application by relying less on a third-party integration. Saloon has a that you can install to enable caching support.
To install the caching functionality into Saloon, install the plugin using Composer.
Next, add the Cacheable
interface and HasCaching
trait to your request or connector. You must define the two methods.
resolveCacheDriver
cacheExpiryInSeconds
When you add the HasCaching
trait onto your connector, every request through the connector will be cached.
Saloon's caching plugin works with different caching drivers that you can use on your request or connector. The plugin comes with the following cache drivers:
PsrCacheDriver (Supports PSR-16 Cache Implementations)
FlysystemDriver (Requires league/flysystem
version 3)
LaravelCacheDriver (Supports any of Laravel's cache disks, requires Laravel)
When Saloon caches a request, it will last a specified amount of time in seconds. You should specify this time in the cacheExpiryInSeconds
method.
Once you have configured the cache driver and expiry, Saloon will automatically cache requests and store them in your requested cache-store. The next time you send a request, the cached response will be automatically swapped out and no real request will be sent.
You may use the isCached()
method to determine if a response is cached.
Saloon will only cache a successful request when the method is either GET or OPTIONS. You can customise this by extending the getCacheableMethods
method where you added the HasCaching
trait.
By default, the cache key is created from the full request URL, the headers that are sent and the query parameters that are used. You may choose to define your own custom cache key. Just extend the protected cacheKey
method where you added the HasCaching
trait. You will get access to the PendingRequest
instance that contains all the request properties.
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.
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.
You may customise when Saloon considers a request as successful. To read more about this,
To view the source code of this plugin, .