-
-
Save carlalexander/7aa149b55ea026a0e046b69d46439817 to your computer and use it in GitHub Desktop.
Designing a class to assemble plugin classes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
Plugin Name: My plugin | |
*/ | |
// Setup class autoloader | |
require_once dirname(__FILE__) . '/src/MyPlugin/Autoloader.php'; | |
MyPlugin_Autoloader::register(); | |
$myplugin = new MyPlugin_Plugin(__FILE__); | |
add_action('wp_loaded', array($myplugin, 'load'); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class MyPlugin_Plugin | |
{ | |
/** | |
* The basename of the plugin. | |
* | |
* @var string | |
*/ | |
private $basename; | |
/** | |
* The plugin event manager. | |
* | |
* @var MyPlugin_EventManagement_EventManager | |
*/ | |
private $event_manager; | |
/** | |
* Flag to track if the plugin is loaded. | |
* | |
* @var bool | |
*/ | |
private $loaded; | |
/** | |
* The plugin router. | |
* | |
* @var MyPlugin_Routing_Router | |
*/ | |
private $router; | |
/** | |
* Constructor. | |
* | |
* @param string $file | |
*/ | |
public function __construct($file) | |
{ | |
$this->basename = plugin_basename($file); | |
$this->event_manager = new MyPlugin_EventManagement_EventManager(); | |
$this->loaded = false; | |
$this->router = new MyPlugin_Routing_Router(); | |
} | |
/** | |
* Loads the plugin into WordPress. | |
*/ | |
public function load() | |
{ | |
if ($this->loaded) { | |
return; | |
} | |
foreach ($this->get_routes() as $route) { | |
$this->router->add_route($route); | |
} | |
foreach ($this->get_subscribers() as $subscriber) { | |
$this->event_manager->add_subscriber($subscriber); | |
} | |
$this->loaded = true; | |
} | |
/** | |
* Get the plugin routes. | |
* | |
* @return MyPlugin_Routing_Route[] | |
*/ | |
private function get_routes() | |
{ | |
return $this->event_manager->filter('myplugin_routes', array( | |
// Our plugin routes | |
)); | |
} | |
/** | |
* Get the plugin event subscribers. | |
* | |
* @return MyPlugin_EventManagement_SubscriberInterface[] | |
*/ | |
private function get_subscribers() | |
{ | |
return $this->event_manager->filter('myplugin_subscribers', array( | |
new MyPlugin_Subscriber_CustomPostTypeSubscriber(), | |
)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment