admin管理员组

文章数量:1122846

I am using WP_Object_Cache to store entries under a group. This is done during an api request and I would like to return the total number of cached entries to the user in the response. After looking on the documentation there seems to be no way to get a list of all entries stored under a specific group without knowing the actual key for each entry.

public function handleRequest(\WP_REST_Request $request): ?\WP_REST_Response
{
   global $wp_object_cache;
   $content = $request->get_body();
   if ($content) {
     $group = 'sample';
     $key = hash('sha256', $content);
     $entry = $wp_object_cache->get($key, $group);
     if (!$entry) {
       // Process request.
       $wp_object_cache->set($key, $content, $group);
     }
     return new \WP_REST_Response([
       'status' => 200,
       'response' => [
         'entry' => $content,
         // Here I would like to return the number of cached entries.
         'numberOfEntries' => 1,
       ],
     ]);
   }
}

I would like to do something like 'numberOfEntries' => array_keys($wp_object_cache->get_multiple('*', $group)), but this only works if I actually already know all the keys for the stored entries?

I am using WP_Object_Cache to store entries under a group. This is done during an api request and I would like to return the total number of cached entries to the user in the response. After looking on the documentation there seems to be no way to get a list of all entries stored under a specific group without knowing the actual key for each entry.

public function handleRequest(\WP_REST_Request $request): ?\WP_REST_Response
{
   global $wp_object_cache;
   $content = $request->get_body();
   if ($content) {
     $group = 'sample';
     $key = hash('sha256', $content);
     $entry = $wp_object_cache->get($key, $group);
     if (!$entry) {
       // Process request.
       $wp_object_cache->set($key, $content, $group);
     }
     return new \WP_REST_Response([
       'status' => 200,
       'response' => [
         'entry' => $content,
         // Here I would like to return the number of cached entries.
         'numberOfEntries' => 1,
       ],
     ]);
   }
}

I would like to do something like 'numberOfEntries' => array_keys($wp_object_cache->get_multiple('*', $group)), but this only works if I actually already know all the keys for the stored entries?

Share Improve this question asked May 11, 2024 at 5:15 CyclonecodeCyclonecode 1,1641 gold badge9 silver badges32 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

Here is an untested one-liner, counting the cache data array returned from the magic __get method, with a fallback to an empty array if the group key is not set:

'numberOfEntries' => count( $wp_object_cache->cache[$group] ?? [] );

Another approach is to consider bindTo to access the private cache array of the $wp_object_cache instance via closure.

本文标签: rest apiHow can I get the number of items stored under a cache group