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
2929
3030use Psr \Http \Message \ServerRequestInterface ;
3131
32- // Global (instance-wide) scope
33- // This computation runs at instance cold-start
34- $ instanceVar = _heavyComputation ();
35-
3632function 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 ;
You can’t perform that action at this time.
0 commit comments