keys. See remember_stored(). * * @var array */ const STORED = array( 'space_members' => array( 'counts' ), ); /** * Returns a cached value or computes and stores it. * * @param string $family Family name, for example "spaces". * @param string $key Key inside the family. * @param callable $callback Computes the value on a miss. * @return mixed */ public static function remember( $family, $key, callable $callback ) { $full = $family . ':' . $key . ':' . wp_cache_get_last_changed( self::GROUP . '_' . $family ); $found = false; $value = wp_cache_get( $full, self::GROUP, false, $found ); if ( $found ) { return $value; } $value = call_user_func( $callback ); wp_cache_set( $full, $value, self::GROUP, HOUR_IN_SECONDS ); return $value; } /** * Like remember(), but the value also survives between page loads on sites * without a persistent object cache, where remember() alone would run the * query again on every request. Meant for small values that are costly to * compute and rarely change. The key must be listed in STORED so flush() * can expire it. * * @param string $family Family name. * @param string $key Key inside the family, listed in STORED. * @param callable $callback Computes the value on a miss. * @param int $ttl Seconds to keep the stored copy. Short on purpose: a request that * computed the value just before a flush can store its older copy. * @return mixed */ public static function remember_stored( $family, $key, callable $callback, $ttl = 600 ) { return self::remember( $family, $key, static function () use ( $family, $key, $callback, $ttl ) { // A persistent object cache already keeps remember() values between requests. if ( wp_using_ext_object_cache() ) { return call_user_func( $callback ); } $name = self::stored_name( $family, $key ); $stored = get_transient( $name ); if ( is_array( $stored ) && array_key_exists( 'value', $stored ) ) { return $stored['value']; } $value = call_user_func( $callback ); set_transient( $name, array( 'value' => $value ), $ttl ); return $value; } ); } /** * Expires every cached value of a family. * * @param string $family Family name. * @return void */ public static function flush( $family ) { // Same effect as wp_cache_set_last_changed(), which needs WordPress 6.3. wp_cache_set( 'last_changed', microtime(), self::GROUP . '_' . $family ); if ( isset( self::STORED[ $family ] ) && ! wp_using_ext_object_cache() ) { foreach ( self::STORED[ $family ] as $key ) { delete_transient( self::stored_name( $family, $key ) ); } } } /** * Transient name of a stored value. * * @param string $family Family name. * @param string $key Key inside the family. * @return string */ private static function stored_name( $family, $key ) { return 'spacebay_c_' . $family . '_' . $key; } }