Instantiating classes in constructor vs in a method

I’m writing a plugin, and for the most part I’m following the plugin boilerplate with the addition of autoloading and namespacing.

When running the main class, where you include methods to run in the constructor

function run_plugin_name() {
$plugin = new Plugin_Name();
$plugin->run();
}
run_plugin_name();

in the Plugin_Name class we have

class Plugin_Name {

protected $loader;

protected $plugin_name;

protected $version;

public function __construct() {
if ( defined( ‘PLUGIN_NAME_VERSION’ ) ) {
$this->version = PLUGIN_NAME_VERSION;
} else {
$this->version = ‘1.0.0’;
}
$this->plugin_name = ‘plugin-name’;
$this->load_dependencies();
$this->set_locale();
$this->define_admin_hooks();
$this->define_public_hooks();
}
}

I am wondering what is the best practice, and if there is any benefit if I define the objects that will be used in the add_action / add_filter methods inside the constructor like

public function __construct() {
if ( defined( ‘PLUGIN_NAME_VERSION’ ) ) {
$this->version = PLUGIN_NAME_VERSION;
} else {
$this->version = ‘1.0.0’;
}
$this->plugin_name = ‘plugin-name’;

$this->admin = new Admin( $this->plugin_name, $this->version );

$this->load_dependencies();
$this->set_locale();
$this->define_admin_hooks();
$this->define_public_hooks();
}

and then use this inside, say define_admin_hooks() method

private function define_admin_hooks() {
$this->loader->add_action( ‘admin_enqueue_scripts’, $this->admin, ‘enqueue_styles’ );
$this->loader->add_action( ‘admin_enqueue_scripts’, $this->admin, ‘enqueue_scripts’ );
}

Or should I do it like it’s done in the plugin boilerplate

private function define_admin_hooks() {
$plugin_admin = new Admin( $this->get_plugin_name(), $this->get_version() );
$this->loader->add_action( ‘admin_enqueue_scripts’, $plugin_admin, ‘enqueue_styles’ );
$this->loader->add_action( ‘admin_enqueue_scripts’, $plugin_admin, ‘enqueue_scripts’ );
}

The reason I’m asking is because I have several methods where I add my actions and filters, based on the plugin functionality, and there are some classes that I’m using in both methods. So it seems better to have them in the constructor and then just use them in the methods.

That way I’m not breaking the DRY principle.

Is my reasoning correct?

Read more here:: Instantiating classes in constructor vs in a method

Leave a Reply

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