OOP development and hooks

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 AdminController( $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 AdminController( $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 AdminInteractWithVimeo();
$this->loader->add_action ( ‘admin_init’, $interactWithVimeo, ‘setCredentials’);

$cpt = new AdminCustomPostType();

// 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 AdminSettingsPage();

// 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 AdminMyExensiveClassWithAlotOfMethods();
$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.

Read more here:: OOP development and hooks

Leave a Reply

Your email address will not be published. Required fields are marked *