Skip to content

Instantly share code, notes, and snippets.

@tommcfarlin
Created August 14, 2018 14:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tommcfarlin/274b69d0fc1e39aaf51384287240cea6 to your computer and use it in GitHub Desktop.
Save tommcfarlin/274b69d0fc1e39aaf51384287240cea6 to your computer and use it in GitHub Desktop.
[WordPress] Organizing Subscribers, WordPress Types, and Views
<?php
class AcmeMetaBoxSubscriber extends AbstractSubscriber
{
public function __construct(string $hook)
{
parent::__construct($hook);
}
public function load()
{
(new AcmeMetaBox())->render();
}
}
<?php
class AcmeMetaBox extends AbstractMetaBox
{
public function render()
{
add_meta_box(
'acme-data',
'Acme Data',
[$this, 'display'],
$this->postType,
'normal',
'high'
);
}
public function display()
{
include_once plugin_dir_path(__FILE__).'Views/acme-data.php';
}
}
<div class="acme-data-metabox">
<?php echo __('Acme Data', 'acme-meta-box'); ?>
<p class="description">
This is the content of the metabox.
</p>
</div>
<?php
class Plugin
{
private $registry;
public function __construct(Registry $registry)
{
$this->registry = $registry;
}
public function start()
{
array_map(function ($subscriber) {
add_action($subscriber->getHook(), [$subscriber, 'load']);
}, $this->registry->getRegisteredSubscribers());
}
}
<?php
// Setup a filter so we can retrieve the registry throughout the plugin.
$registry = new Registry();
add_filter('acmeApiRegistry', function () use ($registry) {
return $registry;
});
// Register all of our objects with a basic registry.
$registry->add('acmeMetaBoxSubscriber', new AcmeMetaBoxSubscriber('add_meta_boxes'));
$plugin = new Plugin($registry);
$plugin->start();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment