Home > Blog > RedBean PHP and WordPress - A match made in plugin development heaven?

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

26 Nov 2010

Sometimes, developing an extension with WordPress requires database access. Not just simple grab-a-few-rows database access, but the kind of access where an ORM could really speed up development.

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 mostly procedural WordPress would not be easy. Then I discovered RedBean.

<?php

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)

<?php

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:

<?php

$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.

I don't email very often

Powered by Buttondown

Profile picture

Jordan West

Sydney, Australia

jordan [at] west.io | twitter | github | youtube | instagram