Make WordPress Core

Opened 15 years ago

Closed 13 years ago

#9953 closed feature request (worksforme)

Use Dependency Injection for wpdb Connectors

Reported by: jacobsantos's profile jacobsantos Owned by:
Milestone: Priority: normal
Severity: normal Version:
Component: General Keywords:
Focuses: Cc:


I think I might have written about this before and I apologize about bring it up again, but I'm interested in this again.

Right now, to use mysqli or PDO, you would have to write your own class that replaces wpdb completely. The reason for this is that all classes are going to use wpdb. You could also update $wpdb, but this isn't the best solution because you are still required to implement all of the methods in wpdb and keep them updated.

The solution I propose is to use Dependency Injection pattern and instead of using straight mysql calls, call a class that has the functions in a wrapper. I would suggest removing debugging and error calls as well and separating them out into their own classes and using the same DI pattern as well for them (it is slightly more difficult to do so for debugging and failure use cases, perhaps including a function if it exists to replace the default one?).

This can be implemented and compatible with PHP4 (it would be with so much hate that it would be done so). I would also go as so far as to have implementations for mysqli and PDO as well for if the user wishes to use them instead.

The implementation would look something like this:

function change_dependency()
    global $wpdb;

    $wpdb->connector( new My_Wpdb_Connector() );

If it was a plugin.

If you want to use the defaults, I'll suggest an constant:

if( defined('WP_USE_MYSQLI') )
    $wpdb->connector( new WordPress_Connector_Mysqli() );
else if( defined('WP_USE_PDO') )
    $wpdb->connector( new WordPress_Connector_Pdo() );
    $wpdb->connector( new WordPress_Connector_MySql() );

in wpdb.php. You could also check for PDO extension, the MySQLi extension, and use one, if it exists. I will say that allowing the user to choose is a better choice, since there might be a really good reason to not use PDO and instead use MySQLi.

Change History (3)

#1 @jacobsantos
15 years ago

  • Type changed from defect (bug) to feature request

#2 @Denis-de-Bernardy
15 years ago

  • Milestone changed from Unassigned to Future Release

#3 @westi
13 years ago

  • Milestone Future Release deleted
  • Resolution set to worksforme
  • Status changed from new to closed

We changed the way require_wp_db() works in 3.1 to make it much easier to extend the base class only replacing what you want to.

I think the solution we have now is good enough and works well.

Note: See TracTickets for help on using tickets.