WordPress: create a widget using code from a plugin class

I’m writing a new WordPress plugin: an audio player written atop the marvellous jPlayer. I wanted to give the user the option to add the audio player via a widget, but as my plugin was written OOP I wasn’t really sure how to register the widget using code from my plugin.

It turns out it wasn’t particularly difficult, but I couldn’t find any documentation about it online, so I figured I’d write this wee post, in the hope that it might come in useful for my fellow WordPressers!

My plugin code is written in OOP:

class MyCoolPlugin {
// All my methods + properties here
}
// Instantiate the class
$cool_plugin = new MyCoolPlugin();

The class contains a method to create the HTML that I want to use for both a shortcode and a widget.

class MyCoolPlugin {
  // Returns the HTML for a shortcode or widget
  function shortcode_widget() {
    return '<p>HTML rocks</p>';
  }
}
// Instantiate the class
$cool_plugin = new MyCoolPlugin();

Register my widget:

class CoolWidget extends WP_Widget {
  function CoolWidget() {
    // Instantiate the parent object
    parent::__construct( false, 'Cool Widget' );
  }
}

Then I can add the HTML from the shorcode_widget method of MyCoolClass like so:

class CoolWidget extends WP_Widget {
  function CoolWidget() {
    // Instantiate the parent object
    parent::__construct( false, 'Cool Widget' );
  }
  function widget($args, $instance) {
    // reuse my plugin's code
    global $cool_plugin;
    echo $cool_plugin->shortcode_widget();
  }
}

Nice. Saves me writing a bunch of code multiple times, which I guess is the main point of OOP!