I’m developing a plugin and am just thinking over best practices. How common is it to have a global object? Currently on plugins_loaded I am creating a global object of my class:

add_action( 'plugins_loaded', array( 'Test_Plugin', 'init' ) );
...
public static function init() {
    global $testerski;
    $testerski = __CLASS__;
    $testerski = new $testerski;
}

This allows me to use the global $testerski to call any variables or methods. Is this a common practice?


My other concern is that since I am creating a global object and from my understanding, any hooks have to have public functions so WordPress can call them. The problem is that I can call these functions meant for hooks from my global object. For example, I have some hooks registered as:

public function __construct() {
    add_action( 'init',             array( $this, 'test_plugin_setup' )             );
    add_action( 'template_include', array( $this, 'test_templates' )                );
    add_filter( 'cron_schedules',   array( $this, 'test_add_monthly_schedule' )     ); 
}

public function test_templates( $template ) {
    ...
}

Which I could technically call using $testerski->test_templates(). Since this function shouldn’t really be called directly and only used for hooks – is there a way I can prevent it from being called directly like this? Is something like this dangerous or am I overthinking it?

I’ve noticed some hooks have warnings, like wp_enqueue_scripts will give you a notice that it was called incorrectly.

1
1

This is not common practice, but it works. A better approach, is to use a class and with the singleton pattern, just like WooCommerce and many others, where you have:

  • A static function (called instance, getInstance…) that:
    • Creates an instance (object) if not already done and returns it
    • Or returns the existing instance

Let’s continue with the WooCommerce example; we used to do this to access the global object:

global $woocommerce; 

Now we do:

WooCommerce::instance();

# Or with the handy Shortcut
WC();

I think you will enjoy reading these:

  • WooCommerce::instance() https://docs.woocommerce.com/wc-apidocs/source-function-WC.html#104-119
  • https://docs.woocommerce.com/wc-apidocs/source-function-WC.html#524-534
  • https://en.wikipedia.org/wiki/Singleton_pattern

You can check the value of current_filter() inside your method, but if I were you, I wouldn’t bother. This is not a threat, and other developers may want to use your code, so don’t block them.

Leave a Reply

Your email address will not be published. Required fields are marked *