-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathindex.php
More file actions
71 lines (60 loc) · 2.39 KB
/
index.php
File metadata and controls
71 lines (60 loc) · 2.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<?php
/**
* Copyright 2020 Google LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
function _heavyComputation(): int
{
return 1 * 2 * 3 * 4 * 5;
}
function _lightComputation(): int
{
return 1 + 2 + 3 + 4 + 5;
}
// [START functions_tips_scopes]
// [START functions_tips_lazy_globals]
use Psr\Http\Message\ServerRequestInterface;
function scopeDemo(ServerRequestInterface $request): string
{
// Heavy computations should be cached between invocations.
// The PHP runtime does NOT preserve variables between invocations, so we
// must write their values to a file or otherwise cache them.
// (All writable directories in Cloud Functions are in-memory, so
// file-based caching operations are typically fast.)
// You can also use PSR-6 caching libraries for this task:
// https://packagist.org/providers/psr/cache-implementation
$cachePath = sys_get_temp_dir() . '/cached_value.txt';
$response = '';
// Because the PHP runtime does NOT cache global variables between
// invocations, there is no benefit to "greedily" initializing them
// in global scope. Thus, we ALWAYS initialize them "lazily" within
// the function itself
if (file_exists($cachePath)) {
// Read cached value from file
$response .= "Reading cached value." . PHP_EOL;
$instanceVar = file_get_contents($cachePath);
} else {
// Compute cached value + write to file
$response .= "Cache empty, computing value." . PHP_EOL;
$instanceVar = _heavyComputation();
file_put_contents($cachePath, $instanceVar);
}
// Lighter computations can re-run on each function invocation.
$functionVar = _lightComputation();
$response .= 'Per instance: ' . $instanceVar . PHP_EOL;
$response .= 'Per function: ' . $functionVar . PHP_EOL;
return $response;
}
// [END functions_tips_lazy_globals]
// [END functions_tips_scopes]