Class autoloading and what this means for plugin developers

In BuddyPress 2.6.0, we introduced class autoloading to help reduce the amount of memory used on your site on any given page request.

Class autoloading is part of our ongoing quest to optimize BuddyPress.

However, one issue that we have seen on the support forums is some BuddyPress plugins might need to be updated to better check for the existence of a BuddyPress class or if a BuddyPress component is active.

For example, some plugins use a class_exists() check to determine if a BuddyPress component is active.

if ( class_exists( 'BP_Group_Extension' ) ) {
            class My_Group_Extension extends BP_Group_Extension {
            }

            bp_register_group_extension( 'My_Group_Extension' );
}

Up until BuddyPress 2.5.3, this was fine. However, in BuddyPress 2.6.0, class_exists( 'BP_Group_Extension' ) will now return true all the time by default. This isn’t great as this can cause a fatal error if the Groups component isn’t enabled and we do not want that!

There are two ways to fix this in your plugin:

1) Change class_exists( 'BP_Group_Extension' ) to class_exists( 'BP_Group_Extension', false )

class_exists() accepts a second boolean parameter to call PHP’s autoloader to check if the class exists. This is true by default. If you set this to false, the class isn’t loaded automatically as part of the class_exists() check, so the return value reflects whether the class has been included in a previous call.

For more info, check out PHP’s class_exists() documentation page:
http://php.net/class_exists

2) Use bp_is_active( 'groups' ) instead of class_exists( 'BP_Group_Extension' )

This is the preferred way.

BuddyPress has a native function to check if a component is active, bp_is_active().

Use bp_is_active( 'groups' ) to check if the Groups component is active in your plugin and that should be it!

If you have any questions, please leave them below.