The $bp global

Way back in the early days of BuddyPress, the $bp global variable was king. Just about everything BuddyPress related was connected to it in some way (other than the template loops themselves.)

This approach is not uncommon. Even WordPress does something similar in wp-settings.php:

$GLOBALS['wp'] = new WP();

The major difference between WordPress and BuddyPress here is that the $wp global has always been a WP() object responsible for setting up the WordPress environment, while our $bp global used to be just a big collection of random attributes.

We’ve been fairly open and relaxed about latching on to the object as a global data store for all of BuddyPress’s runtime variables. Several third-party BuddyPress plugins use it, and our BP_Component interacts with many of its variables directly.

Fast forward to 2012, and $bp is transformed into a real BuddyPress object, complete with methodology and best practices, and ready to be a bit more intelligent than it was in the past. Since then, we’ve slowly removed our dependence on touching the $bp global directly, and instead encapsulated it in a call to buddypress() to retrieve the object into the current scope. You can read more about the overall initiative on Trac Ticket #5138.

This evening, I replaced all of our remaining global touches with one sweeping changeset. In most cases, this should be a completely invisible change that means very little to anyone not working on BuddyPress core. For the small group of us constantly building and maintaining core, this means a few different things:

  • No more defining the $bp global. Use the buddypress() instead.
  • Even though the global is still hanging around for backwards compatibility, touching it directly should be avoided to prevent accidental breakage.
  • We can start to introduce magic getters and setters for commonly referenced or manipulated variables to ensure their evocation and ongoing validity.
  • We can start reliably moving other BuddyPress globals into this object, and architecting what the next generation of extensions to BuddyPress core will look like, and how BuddyPress core will react to them.
  • We can sleep a bit more soundly knowing that the $bp global has an extra layer of protection against being unknowingly overridden by unexpected plugin conflicts or other WordPress environmental oddities. (Though it’s been years since BackPress and BuddyPress were actively loaded together, between BuddyPress, BackPress, and bbPress, the “bp” namespace was very easily polluted.)

Though developer impact should be minimal, this represents a sweeping code change for BuddyPress 2.3 that should not go unrecognized or uncelebrated. This bit of clean-up was years of iteration and testing, and it feels pretty darn good to have it over and done with so we can move on to other more pressing issues.