Skip to content

Instantly share code, notes, and snippets.

@engelen
Last active August 29, 2015 14:03
Show Gist options
  • Save engelen/53e53544bea716564659 to your computer and use it in GitHub Desktop.
Save engelen/53e53544bea716564659 to your computer and use it in GitHub Desktop.
Code is poetry. An implementation of a plugin class structure that allows you to access a plugin class instance without using singletons and without storing a reference to the instance in the global namespace.
<?php
/*
Plugin Name: My Plugin
*/
/**
* Main plugin class
*/
class MyPlugin {
/**
* Constructor
*/
public function __construct() {
// Only add actions and filters here
add_action( 'plugins_loaded', array( $this, 'after_setup' ) );
}
/**
* Fires when My Plugin is fully loaded
*/
public function after_setup() {
/**
* Fires when My Plugin is fully loaded, but no real actions have been performed yet
* At this point, all required files have been included and all actions and filters have been added
*
* @param MyPlugin $myplugin_instance Main My Plugin class instance
*/
do_action( 'myplugin/loaded', $this );
}
}
new MyPlugin();
<?php
/*
Plugin Name: Another Plugin
*/
// Simplified usage example for the setup
class AnotherPlugin {
public $myplugin;
public function __construct() {
// Hook into My Plugin setup callback
add_action( 'myplugin/loaded', array( $this, 'myplugin_loaded' ) );
}
public function myplugin_loaded( $myplugin_instance ) {
// Store reference to My Plugin's main class instance for usage throughout Another Plugin
$this->myplugin = $myplugin_instance;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment