{ WPDB Abstraction }

When working on a WordPress plugin, it may be inevitable that we’ll have to query the database directly. This is done by making use of the $wpdb global, and a series of methods that can make your code messy or inadvertently insecure. I decided to create a base class to handle $wpdb calls, initially for connection and simple SELECT queries.

Note that this class was initially namespaced, so it would be wise to add one or wrap it in a if ( ! class_exists( ‘Connection’ ) ) call. Connection is certainly common enough that collisions with other code is possible.

The constructor accepts the $wpdb global and assigns it to a temporary local $database variable. That is used to check that the DB is still connected with the aptly named check_connection() method. If true, we assign $wpdb to our own private $wpdb property.

We’d use this in a plugin like this: