3

I'm trying to create a simple linkroll widget for displaying recent https://pinboard.in links via their API. To maximize loading speed, I want to cache the linklist in a widget field, as well as the timestamp when it was fetched last.

Now, if a defined time is over, I want to reload the link list via cURL and save it again in the widget field. How to do this from outside of the update() function?

My code:

// display widget
function widget($args, $instance) {

    extract( $args );

    // get widget title
    $title          = apply_filters('widget_title', $instance['title']);

    //  get options
    $token          = $instance['token'];
    $tags           = $instance['tags'];
    $unread         = $instance['unread'];
    $range          = $instance['range'];

    // update linklist based on cache validity
    $isvalid = $this->_check_valid_cache( $instance['expires'], $range );
    if ( $isvalid === TRUE ) {
        $cache         = $instance['cache'];
        $expires       = $instance['expires'];
    } else {
        $cache         = $this->_get_recent( $token );
        $expires       = $isvalid;
        /* --> does not work!! */
        $this->update($instance, $instance);
    }
    /* ...display widget... */

}

1 Answer 1

3

Huh. It had never actually occurred to me to use widget instance as cache. I hadn't ever seen such implementation either.

This is quite an original idea, and as such it is hard to accurately point out benefits and issues with implementation. For starters update() doesn't actually save anything, it just used as check for actual save and I won't say where saving even happens from quick look because it's abstracted deeper.

From my experience the more traditional implementation would be to cache using more conventional approach (such as transients) and tie it to API, not to widget.

As argument for that imagine user puts two different instances of widget in two different sidebars, but configures them the same way. They will be polling API at double rate, while they actually need exactly same data from API and could (and should) share it.

2
  • +1. Even if the more-than-one widget issue can be solved using a static variable, using transient or cache api has the benefit to use advanced object cache when available.
    – gmazzap
    Commented Oct 25, 2014 at 20:14
  • I didn't even know about the transient API... thanks @Rarst! Commented Oct 25, 2014 at 22:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.