File tree Expand file tree Collapse file tree 1 file changed +17
-8
lines changed Expand file tree Collapse file tree 1 file changed +17
-8
lines changed Original file line number Diff line number Diff line change @@ -29,16 +29,25 @@ function _lightComputation(): int
29
29
30
30
use Psr \Http \Message \ServerRequestInterface ;
31
31
32
- // Global (instance-wide) scope
33
- // This computation runs at instance cold-start
34
- $ instanceVar = _heavyComputation ();
35
-
36
32
function scopeDemo (ServerRequestInterface $ request ): string
37
33
{
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.
42
51
$ functionVar = _lightComputation ();
43
52
44
53
$ response = 'Per instance: ' . $ instanceVar . PHP_EOL ;
You can’t perform that action at this time.
0 commit comments