Do not use globals. Ever.
- You don't need your object everywhere. You need it only where your code is running.
- Globals are hard to debug, everyone can write to them or just delete them.
- Unit tests with globals are possible, but awkward. You have to change the global state for each test, ie. something outside of the scope of your testable code.
Make your callbacks object methods instead.
Simple example for such a class:
class DealerInfo
{
/**
* @var \wpdb
*/
private $wpdb;
private $table_name = '';
private $results = [];
public function __construct( \wpdb $wpdb, $table_name )
{
$this->wpdb = $wpdb;
$this->table_name = $table_name;
}
public function entry( $id )
{
if ( empty( $this->results ) )
$this->fetch();
if ( empty( $this->results[ $id ] ) )
return [];
return $this->results[ $id ];
}
private function fetch()
{
$full_table_name = $this->wpdb->prefix . $this->table_name;
$this->results = $this->wpdb->get_results( "SELECT * FROM $full_table_name" );
}
}
Now you can set up that class early, for example on wp_loaded
, and register the method to get the entry details as a callback …
add_action( 'wp_loaded', function() {
global $wpdb;
$dealer_info = new DealerInfo( $wpdb, 'dealer_info' );
add_filter( 'show_dealer_details', [ $dealer_info, 'entry' ] );
});
… and where you want to use echo $dealerInfo['field1'];
, you can now use:
// 4 is the dealer id in the database
$dealer_details = apply_filters( 'show_dealer_details', [], 4 );
if ( ! empty( $dealer_details ) )
{
// print the details
}
Everything is still nicely isolated, except the WP hook API of course.