wpdb->get_row() / get_results – is it possible to return an object instances of my own class?

Is it possible to make wpdb->get_row return an object of a my own custom class instead of stdClass?

Related posts

2 comments

  1. Doesn’t look like it’s possible, at least there doesn’t seem to be an elegant way. get_row() invokes query(), which uses mysql_fetch_object() with a single parameter, ie it’s not possible to pass anything to its class_name parameter.

    So, the only option left would be to extend the wpdb class, implement custom code so that it can return custom classes, and then create an instance of the new class in the global $wpdb variable before WordPress calls require_wp_db(). But that would be some really ugly hack if you ask me.

    Ofcourse you could always create instances of your custom classes manually and populate them from the retreived stdClass instance, just like WordPress does:

    http://core.trac.wordpress.org/browser/trunk/wp-includes/post.php#L605

    public function __construct( $post ) {
        foreach ( get_object_vars( $post ) as $key => $value )
            $this->$key = $value;
    }
    
  2. It is poorly documented but you can replace the database class by adding a “Drop-In” named db.php in the content directory. You could certainly make it return any object you want that way, but it would still need to be compatible with what WordPress expects, or things would break.

    Reference

    http://hakre.wordpress.com/2010/05/01/must-use-and-drop-ins-plugins/

    And here is a plugin that includes such a file:
    http://plugins.trac.wordpress.org/browser/wordpress-database-abstraction/trunk/wp-db-abstraction/db.php

Comments are closed.