2424trait RequestScopedCache
2525{
2626
27+ static function store (){
28+ return Cache::store (config ('cache.request_scope_cache_store ' , 'array ' ));
29+ }
2730 /**
2831 * @return string
2932 */
@@ -36,34 +39,12 @@ static function getScopeId():string{
3639 $ time = time ();
3740 $ sessionId = Session::getId ();
3841 $ uuid = Uuid::uuid4 ()->toString ();
39- /*Log::debug
40- (
41- sprintf
42- (
43- "RequestScopedCache::getScopeId scope is empty ip %s time %s sessionId %s uuid%s .",
44- $ip , $time, $sessionId, $uuid
45- )
46- );*/
47-
4842 $ requestId = md5 (sprintf ("%s.%s.%s.%s " , $ ip , $ time , $ sessionId , $ uuid ));
49-
50- /*Log::debug
51- (
52- sprintf
53- (
54- "RequestScopedCache::getScopeId setting request id %s.",
55- $requestId
56- )
57- );*/
58-
5943 $ request ->headers ->set ('X-Request-ID ' , $ requestId );
60-
6144 $ _SERVER ['HTTP_X_REQUEST_ID ' ] = $ requestId ;
6245
6346 }
6447
65- //Log::debug(sprintf("RequestScopedCache::getScopeId retrieving request id %s" , $requestId));
66-
6748 return $ requestId ;
6849 }
6950
@@ -86,23 +67,21 @@ function getRequestKey(string $serializeName, int $id, ?string $expand = null, a
8667 * @return mixed
8768 */
8869 function cache (string $ key , Closure $ callback ){
70+ $ key = self ::getScopeId ().': ' .$ key ;
71+ $ store = self ::store ();
8972
90- $ scope = self :: getScopeId () ;
73+ $ computed = false ;
9174
92- //Log::debug(sprintf("RequestScopedCache::cache scope %s key %s.", $scope, $key));
75+ $ value = $ store ->remember ($ key , now ()->addSeconds (30 ), function () use ($ callback , &$ computed , $ key ) {
76+ $ computed = true ; // closure ran => MISS
77+ Log::debug ('RequestScopedCache MISS ' , ['key ' => $ key ]);
78+ return $ callback ();
79+ });
9380
94- $ res = Cache::tags ($ scope )->get ($ key );
95- if (!empty ($ res )){
96- $ json_res = gzinflate ($ res );
97- $ res = json_decode ($ json_res ,true );
98- //Log::debug(sprintf("RequestScopedCache::cache scope %s key %s cache hit res %s.", $scope, $key, $json_res));
99- return $ res ;
81+ if (!$ computed ) {
82+ Log::debug ('RequestScopedCache HIT ' , ['key ' => $ key ]);
10083 }
10184
102- $ res = $ callback ();
103- $ json = json_encode ($ res );
104- //Log::debug(sprintf("RequestScopedCache::cache scope %s key %s res %s adding to cache.", $scope, $key, $json));
105- Cache::tags ($ scope )->add ($ key , gzdeflate ($ json , 9 ));
106- return $ res ;
85+ return $ value ;
10786 }
108- }
87+ }
0 commit comments