Skip to content

Commit fa17dc2

Browse files
author
ace-n
committed
Use file caching
1 parent a805939 commit fa17dc2

File tree

1 file changed

+17
-8
lines changed

1 file changed

+17
-8
lines changed

functions/tips_scopes/index.php

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -29,16 +29,25 @@ function _lightComputation(): int
2929

3030
use Psr\Http\Message\ServerRequestInterface;
3131

32-
// Global (instance-wide) scope
33-
// This computation runs at instance cold-start
34-
$instanceVar = _heavyComputation();
35-
3632
function scopeDemo(ServerRequestInterface $request): string
3733
{
38-
global $instanceVar;
39-
40-
// Per-function scope
41-
// This computation runs every time this function is called
34+
// Heavy computations should be cached between invocations.
35+
// The PHP runtime does NOT preserve variables between invocations, so we
36+
// must write their values to a file.
37+
// (All writable directories in Cloud Functions are in-memory, so these
38+
// operations are typically fast.)
39+
$cachePath = '/tmp/cached_value.txt';
40+
41+
if (file_exists($cachePath)) {
42+
// Read cached value from file
43+
$instanceVar = file_get_contents($cachePath);
44+
} else {
45+
// Compute cached value + write to file
46+
$instanceVar = _heavyComputation();
47+
file_put_contents($cachePath, $instanceVar);
48+
}
49+
50+
// Lighter computations can re-run on each function invocation.
4251
$functionVar = _lightComputation();
4352

4453
$response = 'Per instance: ' . $instanceVar . PHP_EOL;

0 commit comments

Comments
 (0)