Skip to content

Instantly share code, notes, and snippets.

@carlalexander
Last active January 27, 2024 14:06
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carlalexander/7aa149b55ea026a0e046b69d46439817 to your computer and use it in GitHub Desktop.
Save carlalexander/7aa149b55ea026a0e046b69d46439817 to your computer and use it in GitHub Desktop.
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