Tinkerwell 4 is out now! See what's new or buy now.
Tinkerwell background image
Tinkerwell Logo Tinkerwell
Go back to Blog

Tinkerwell Shorts: Using the cache for heavy operations

Sometimes you run heavy operations in Tinkerwell to gather some data before you process it. You can speed the development of your Tinkerwell snippet by using the cache of your application for this.

In our example, we're fetching repositories from GitHub and work on them during the script. We want to memorize the API request and only do it once because that's the heaviest operating within our snippet and it always returns the same result.

For this, we run the script and adding the result to the Laravel Cache within the first run. After that, we use a comment to ignore this line and only rely on the cached information for further requests. With this workaround, we are able to instantly have the API result available and don't need to wait for the Http call every time that the code runs.

Try it out with Tinkerwell:

// storing the result in the cache for 10 seconds
Cache::put('resource', Http::get('https://api.github.com/orgs/beyondcode/repos')->json(), 10);

After the first run, simply grab the result from the cache:

 
// Cache::put('resource', Http::get('https://api.github.com/orgs/beyondcode/repos')->json(), 10);
 
collect(Cache::get('resource')) /*?->count()*/
->filter(function ($repo) {
$repo['full_name'];
return Str::contains($repo['full_name'], 'laravel');
}) /*?->count()*/
->map(function ($repo) {
return $repo['full_name'];
});

Make sure to set a sensible expiration timer for this cache object that matches your needs. It can be 300 for 10 minutes or 3600 for one hour but make sure there is something set, otherwise you'll cache this forever.

Jake Bennett, Director of Technology and Innovation
“The ability to SSH directly into a server and run diagnostics directly from Tinkerwell is insanely amazing! Can't imagine doing development without it at this point.”
Jake Bennett

Director of Technology and Innovation

Johannes Güntner, Creator of CustomBlocks
“The amount of time and nerves I save with Tinkerwell is insane. Especially for setting up any new packages, api-requests, validating new implementations and writing tests.”
Johannes Güntner

Creator of CustomBlocks

Tinkerwell: The PHP Scratchpad

The must-have companion to your favorite IDE. Quickly iterate on PHP code within the context of your web application.

Buy now Learn more