Extending WP_User class and using this sub-class during the whole lifecycle

If I did understand well, we need to cache a value retrieved from another REST service, from the login to logout of the user on the wordpress installation, so we will hook into this wp_login to get the value and cache it using Transient API, Options API or a persistent caching plugin.

add_action('wp_login', 'my_get_and_cache_rest_value');
function my_get_and_cache_rest_value ($user_login, $user) {
    // do your rest call
    // cache it using Transient API, Options API or a persistent caching plugin
}

We can then extend the WP_User object and set a our magic calls to get the data we want from the cache.

class MY_User extends WP_User {
    // no constructor so WP_User's constructor is used

    // method to get cached data
    function getMyCachedData() {
        // get data via my cache solution
        if ( ! isset( $this->data->myData ) )
            $this->data->myData = my_get_cached_data( $this->ID );

        return $this->data->myData;
    }

    // magic method to detect $user->my_data
    function __get( $key ) {
        if ( $key == 'my_data' )
        {
            return $this->getMyCachedData();
        }
        else
        {
            // fallback to default WP_User magic method
            return parent::__get( $key );
        }
    }    
}

I hope this would help someone, and cheers to @Daniel.

Leave a Comment