I'm currently working on writing my first OOP Plugin for Wordpress.
To help out a little bit with structure I looked for, and found, a boiler plate that sets up the basics for me.
In Main.php
there's a method that loads JS and CSS assets for admin:
/**
* Register all of the hooks related to the admin area functionality
* of the plugin.
*
* @since 0.1.0
* @access private
*/
private function define_admin_hooks() {
$plugin_admin = new Admin\Controller( $this->get_plugin_name(), $this->get_version(), $this->get_plugin_path() );
$this->loader->add_action( 'admin_enqueue_scripts', $plugin_admin, 'enqueue_styles' );
$this->loader->add_action( 'admin_enqueue_scripts', $plugin_admin, 'enqueue_scripts' );
}
So far, so good. But as my plugin grows in complexity, it feels like this method is gonna get unwieldy with alot of hooks.
Here's an example with a CPT setup and a setting page added
/**
* Register all of the hooks related to the admin area functionality
* of the plugin.
*
* @since 0.1.0
* @access private
*/
private function define_admin_hooks() {
$plugin_admin = new Admin\Controller( $this->get_plugin_name(), $this->get_version(), $this->get_plugin_path() );
$this->loader->add_action( 'admin_enqueue_scripts', $plugin_admin, 'enqueue_styles' );
$this->loader->add_action( 'admin_enqueue_scripts', $plugin_admin, 'enqueue_scripts' );
$interactWithVimeo = new Admin\InteractWithVimeo();
$this->loader->add_action ( 'admin_init', $interactWithVimeo, 'setCredentials');
$cpt = new Admin\CustomPostType();
// Create the custom post type
$this->loader->add_action ( 'init', $cpt, 'create_post_type' );
// Remove post row actions
$this->loader->add_filter ( 'post_row_actions', $cpt, 'remove_row_actions', 10, 2 );
$settingsPage = new Admin\SettingsPage();
// Add the settings page to CPT menu
$this->loader->add_action ( 'admin_menu', $settingsPage, 'add_settings_page' );
}
At this point I'm wondering if it would be better to simply setup the different classes to load their own hooks within themselves to avoid the clutter in Main.php
Such as
/**
* Register all of the hooks related to the admin area functionality
* of the plugin.
*
* @since 0.1.0
* @access private
*/
private function define_admin_hooks() {
$myExensiveClassWithAlotOfMethods = new Admin\MyExensiveClassWithAlotOfMethods();
$this->loader->add_action ( 'admin_init', $myExensiveClassWithAlotOfMethods, 'init' );
}
And the init method in the class then contains all the hooks that the class needs.
Is this a bad idea? There seems to be different ways to do it of course. I'm just curious which approach seems to be inline with the boiler plate.
add_action
a one-liner (and should be better for memory). But will switch to a more "dependancy injection" style soonclass
should only initialize its own hooks, and if the class instantiates other classes, let the classes initialize their own hooks. There are exceptions, but that depend on your code.