Saloon
GithubOfficial BookSponsor
v3
v3
  • 🀠Saloon
  • Upgrade
    • πŸͺ„What's new in v3
    • 🌳Upgrading from v2
  • The Basics
    • ⬇️Installation
    • πŸ”ŒConnectors
    • βœ‰οΈRequests
    • πŸ”Authentication
    • 🎁Sending Body/Data
      • JSON Body
      • Multipart Form Body
      • XML Body
      • URL Encoded Body (Form)
      • String / Plain Text Body
      • Stream Body
    • πŸš€Sending Requests
    • πŸ“‘Responses
    • πŸ”₯Handling Failures
    • πŸ”ŽDebugging
    • βœ…Testing
  • Digging Deeper
    • πŸ›ΈData Transfer Objects
    • ✨Building SDKs
    • ☝️Solo Requests
    • 🎯Retrying Requests
    • ⏸️Delaying Requests
    • 🏎️Concurrency & Pools
    • πŸ”‘OAuth2
      • Authorization Code Grant
      • Client Credentials Grant
    • πŸ’«Middleware
    • ⛩️PSR Support
  • Installable Plugins
    • πŸ“šPagination
      • Paged Pagination
      • Limit/Offset Pagination
      • Cursor Pagination
      • Custom Pagination
    • β›΅Laravel Plugin
    • πŸ”Caching
    • β›”Rate Limit Handler
    • 🏭Auto SDK Generator
    • 🀠Lawman
    • πŸ‡XML Wrangler
    • πŸ—οΈBuilding Your Own Plugins
  • Conclusion
    • πŸ“˜Official Book!
    • πŸ“”How-to Guides
      • Improving Speed With Laravel
      • Per-request Authentication
    • πŸ“–Tutorials & Blog Posts
    • πŸŽ–οΈShowcase
    • πŸ’₯Known Issues
    • πŸ€—Credits
    • ❀️Support Saloon
Powered by GitBook
On this page
  • Installation
  • Configuration
  • Cache Drivers
  • Expiry
  • Caching Requests
  • Customising the cache key
  • Invalidating the current cache
  • Temporarily Disabling Caching
  • Source Code
Edit on GitHub
  1. Installable Plugins

Caching

PreviousLaravel PluginNextRate Limit Handler

Last updated 1 year ago

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.

Installation

To install the caching functionality into Saloon, install the plugin using Composer.

composer require saloonphp/cache-plugin "^3.0"

Configuration

Next, add the Cacheable interface and HasCaching trait to your request or connector. You must define the two methods.

  • resolveCacheDriver

  • cacheExpiryInSeconds

<?php

use Saloon\CachePlugin\Contracts\Driver;
use Saloon\CachePlugin\Traits\HasCaching;
use Saloon\CachePlugin\Contracts\Cacheable;

class GetServersRequest extends Request implements Cacheable
{
    use HasCaching;

    // ...
    
    public function resolveCacheDriver(): Driver
    {
        //
    }
    
    public function cacheExpiryInSeconds(): int
    {
        //
    }
}

When you add the HasCaching trait onto your connector, every request through the connector will be cached.

Cache Drivers

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)

use Saloon\CachePlugin\Drivers\PsrCacheDriver;

public function resolveCacheDriver(): Driver
{
    // This example uses the PhpArrayAdapter from 
    // the symfony/cache library.
    
    return new PsrCacheDriver(new PhpArrayAdapter);
}
use Saloon\CachePlugin\Drivers\FlysystemDriver;

public function resolveCacheDriver(): Driver
{
    // This example uses the "AwsS3V3Adapter" driver
    // that is provided by Flysystem.

    return new FlysystemDriver(
        new Filesystem(new AwsS3V3Adapter($s3Client, 'bucket-name'))
    );
}
use Illuminate\Support\Facades\Cache;
use Saloon\CachePlugin\Drivers\LaravelCacheDriver;

public function resolveCacheDriver(): Driver
{
    // This example uses Redis cache store that
    // Laravel provides.

    return new LaravelCacheDriver(Cache::store('redis'));
}

Expiry

When Saloon caches a request, it will last a specified amount of time in seconds. You should specify this time in the cacheExpiryInSeconds method.

public function cacheExpiryInSeconds(): int
{
    return 3600; // One Hour
}

Caching Requests

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.

Checking if a response is cached

You may use the isCached() method to determine if a response is cached.

<?php

$forge = new ForgeConnector;

$response = $forge->send(new GetServersRequest);
$response->isCached(); // false

// Next time it is sent...

$response = $forge->send(new GetServersRequest);
$response->isCached(); // true

When will Saloon cache a request?

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.

<?php

use Saloon\Enums\Method;

class GetServersRequest extends Request implements Cacheable
{
    use HasCaching;
    
    protected function getCacheableMethods(): array
    {
        return [Method::GET, Method::OPTIONS, Method::POST];
    }
}

Customising the cache key

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.

<?php

use Saloon\Http\PendingRequest;

class GetServersRequest extends Request implements Cacheable
{
    use HasCaching;
    
    protected function cacheKey(PendingRequest $pendingRequest): ?string
    {
        return 'custom-cache-key';
    }
}

Invalidating the current 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.

<?php

$forge = new ForgeConnector;

$request = new GetServersRequest;
$request->invalidateCache();

$response = $forge->send($request);

Temporarily Disabling 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.

<?php

$forge = new ForgeConnector;

$request = new GetServersRequest;
$request->disableCaching();

$response = $forge->send($request);

Source Code

You may customise when Saloon considers a request as successful. To read more about this,

To view the source code of this plugin, .

πŸ”
first-party plugin
click here
click here.