Created
September 9, 2024 12:43
-
-
Save renatofrota/a0e43ea4b02ec872c858cd2ccea4b90d to your computer and use it in GitHub Desktop.
Remember: a simple Laravel / PHP volatile runtime cache
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// save this file as ./app/Helpers/Remember.php | |
namespace App\Helpers { | |
class Remember | |
{ | |
public static array $that = []; | |
} | |
} | |
// this is all - the part below is just usage example | |
namespace { | |
use App\Helpers\Remember; | |
// here we are back to the root namespace | |
// https://www.php.net/manual/en/language.namespaces.definitionmultiple.php | |
// example on how to process a given value/array and save results to the | |
// volatile runtime cache (Remember::$that) and optionally regular cache | |
if (! function_exists('pow_once')) { | |
function pow_once(mixed $input, bool $distinct = true): mixed | |
{ | |
if (!$is_array = is_array($input)) $input = [md5(json_encode($input)) => $input]; | |
foreach ($input as $key => $value) { | |
// distinct [0 => some_value] and [0 => other_value]? | |
// pass false to treat key as an idempotent cache key | |
// and disregard what is sent as value on other calls | |
$thing = $distinct ? md5($key . json_encode($value)) : $key; | |
// you can retrieve data from runtime (volatile) cache only: | |
$output[$key] ??= Remember::$that[$thing] ??= null; | |
// or optionally use regular (persistent) cache as fallback: | |
// $output[$key] ??= Remember::$that[$thing] ??= \Illuminate\Support\Facades\Cache::get($thing); | |
if (is_null($output[$key])) { | |
// process $key/$value | |
$pow = ($is_array ? $key : $value) ** $value; | |
// feed the output array | |
$output[$key] = ($is_array ? $key : $value) . '^' . $value . ' = ' . $pow; | |
// save to regular (persistent) cache | |
// Cache::put($thing, $output[$key], now()->addMinutes(30)); | |
// save to runtime (volatile) cache (suffix added for debug purposes) | |
Remember::$that[$thing] = $output[$key] . " (from cache)"; | |
} | |
} | |
// return the output array or 1st element when input is not array | |
return $is_array ? $output : reset($output); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment