RedBean PHP and Wordpress - A match made in plugin development... heaven?

Wordpress is probably my least favourite place to be coding. I know many die hard PHP fans will argue with me here, but writing procedural PHP code is not my thing. I’d much rather be working in a nice OOP environment such as that of Kohana 3.

Nonetheless, Wordpress is the defacto standard in CMS these days, and there is no denying that it has the widest variety of plugins and themes available. So while Wordpress isn’t too efficient to code with, I thought I would work out how to make developing a plugin with Wordpress a little less painful and more efficient.

Since the plugin I’m working on does quite a bit of data access/manipulation (WP options are not an option!), I quickly discovered the limitations of $wpdb, and started searching for an ORM. Of course I thought integrating an entire ORM system into the procedural Wordpress would not be easy. Then I discovered RedBean.

require('rb.php');
R::setup("mysql:host=".DB_HOST.";dbname=".DB_NAME,
          DB_USER, DB_PASSWORD);

Done.

If you want to include the Wordpress table prefix, put this at the top of your module (or another file if you prefer)

class WPBeanFormatter implements RedBean_IBeanFormatter{
    public function formatBeanTable($table) {
        global $table_prefix;
        return $table_prefix."$table";
    }
    public function formatBeanID( $table ) {
        return "id";
    }
}
R::$writer->setBeanFormatter(new WPBeanFormatter());

From there you can do all your data access through the static R class. The greatest thing about RedBean is that you can write your code before you have even created database tables – RedBean will detect the data you are saving and create/adjust the tables and columns to fit your data. Once development is finished, you can ‘freeze’ RedBean preventing it from modifying the database structure. Here is some sample code to save an object:

$product = R::dispense("product");
$product->name = "Super Gadget";
$product->price = 299;
$product->description = "A dicer, slicer, fax machine".
                           "and coffee maker all-in-one!";
$id = R::store($product);

Get RedBean PHP here.