add wrapper class which allows using library through a single clean i…
…nterface
This is a great library, the one issue I had with it was the way the API for using this requires you to add highly specific API calls throughout your codebase. To simplify this I created a wrapper that accepts in its constructor a cache key, a default_value to return if the cache is not yet warm, the length of time to cache the object, the function to call to regenerate the cached data and optionally any arguments.
It exposes a bunch of mutators for on the fly updating of objects along with a get method to retrieve your data.
An example usage of this would be something like the following oversimplified example:
$api_call = function ( $parameter ) {
//expensive API call simulation
sleep( 2 );
return $parameter . time();
};
$cache_key = 'expensive-api-call';
$async = new \TenUp\AsyncTransients\Transient_Wrapper( $cache_key, 'default-value-cache-not-yet-warm',
MINUTE_IN_SECONDS * 60, $api_call,
array( 'api_parameter_1' ) );
$before = microtime( true );
$val = $async->get();
?><p>Cache value:</p>
<pre><?php
var_dump( $val );
?></pre><?php
echo '<p>Time taken: ' . (float)( microtime( true ) - $before ) . '</p>';
I also like the original approach because it's more "WordPress-ish". I've just included the function from the namespace to make it more readable:
use function \TenUp\AsyncTransients\get_async_transient;
use function \TenUp\AsyncTransients\set_async_transient;
function get_accessible_posts( $user_id ) {
$post_ids = [];
// ...
set_async_transient( "access-for-$user_id", $post_ids );
return $post_ids;
}
$post_ids = get_async_transient( "access-for-$user_id", 'get_accessible_posts', [ $user_id ] );
// Catch the very first request before the transient exists.
if ( false === $post_ids ) {
$post_ids = get_accessible_posts( $user_id );
}