From a9b3ffe7594a66890bc8e551727ab67690675497 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miloslav=20H=C5=AFla?= Date: Mon, 9 Jan 2023 11:36:16 +0100 Subject: [PATCH] added $dependencies as a Cache::load() 3rd parameter --- readme.md | 8 ++++++++ src/Caching/Cache.php | 2 +- tests/Caching/Cache.load.phpt | 13 +++++++++++-- 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/readme.md b/readme.md index 2df59f89..6b9a1709 100644 --- a/readme.md +++ b/readme.md @@ -131,6 +131,14 @@ $value = $cache->load($key, function (&$dependencies) { ]); ``` +Or using 3rd parameter in the `load()` method, eg: + +```php +$value = $cache->load($key, function () { + return ...; +], [Cache::Expire => '20 minutes']); +``` + In the following examples, we will assume the second variant and thus the existence of a variable `$dependencies`. diff --git a/src/Caching/Cache.php b/src/Caching/Cache.php index 09ac340b..99e59569 100644 --- a/src/Caching/Cache.php +++ b/src/Caching/Cache.php @@ -111,7 +111,7 @@ public function derive(string $namespace): static /** * Reads the specified item from the cache or generate it. */ - public function load(mixed $key, ?callable $generator = null): mixed + public function load(mixed $key, ?callable $generator = null, ?array $dependencies = null): mixed { $storageKey = $this->generateKey($key); $data = $this->storage->read($storageKey); diff --git a/tests/Caching/Cache.load.phpt b/tests/Caching/Cache.load.phpt index 581da666..f64e7e0a 100644 --- a/tests/Caching/Cache.load.phpt +++ b/tests/Caching/Cache.load.phpt @@ -42,6 +42,15 @@ Assert::same('value', $data['data']); Assert::same($dependencies, $data['dependencies']); +$value = $cache->load('key2', fn() => 'value2', $dependencies); +Assert::same('value2', $value); + +$data = $cache->load('key2', fn() => "won't load this value"); +Assert::same('value2', $data['data']); +Assert::same($dependencies, $data['dependencies']); + + + // load twice with fallback, pass dependencies function fallback(&$deps) { @@ -50,8 +59,8 @@ function fallback(&$deps) } -$value = $cache->load('key2', 'fallback'); +$value = $cache->load('key3', 'fallback'); Assert::same('value', $value); -$data = $cache->load('key2'); +$data = $cache->load('key3'); Assert::same('value', $data['data']); Assert::same($dependencies, $data['dependencies']);