Skip to content

Instantly share code, notes, and snippets.

@carlalexander carlalexander/Plugin.php Secret
Last active Jan 3, 2018

Embed
What would you like to do?
Designing a class to assemble plugin classes
<?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');
<?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
You can’t perform that action at this time.