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.