When To Instantiate Classes In WordPress Plugins

The Problem of Premature Instantiation

Prematurely instantiating classes in WordPress plugins can cause several problems. Creating class instances too early can result in unnecessary performance overhead, wasting memory and processor usage. It can also create hidden dependencies that lead to unexpected breakage. Understanding proper instantiation patterns is key to scalable and robust plugin architecture.

Wasted Resources

Instantiating classes on file load regardless of necessity loads code and initializes properties without reason. For low-traffic sites this unnecessary load may not be noticeable. However, on large sites with heavy load or limited resources, needlessly spinning up classes detriments performance and scalability.

Hidden Dependencies

Premature initialization hides dependencies across code. Classes instantiated early are available globally, making dependency chains unclear. This leads to entanglement across logic and breakage when related code changes. Only initializing classes when truly needed limits scope and promotes loose coupling.

Guidelines for Instantiating Classes

Following key guidelines when instantiating classes helps prevent premature initialization issues:

Only Instantiate When Needed

Avoid instantiating classes on file load or other arbitrary early events. Only instantiate when some logic or hook explicitly requires the class. This prevents wasted resources from unnecessary initialization and clearly ties lifecycle to necessity.

Use Dependency Injection Over Globals

When dependencies exist, inject class instances only where required rather than relying on globals. Dependency injection explicitly defines interactions, while global variables hide linkages leading to entanglement across logic.

Lazy Load Expensive Instantiations

For resource intensive classes, use deferred initialization to spin up only when first accessed. This avoids heavy startup load in favor of on-demand lazy loading, improving performance across expected usage.

Instantiating Classes on Plugins Activation

It’s tempting to instantiate key classes on standard plugin hooks like activation. However, activation runs for every plugin on every page load prior to necessity checks, making it too early in most cases.

Activation Runs Early

Even though WordPress triggers plugin activation hooks after plugins load, this event fires on every request before individual necessity logic runs to check if the plugin should run on this page. Activating too early forces resource usage where not needed.

Better Instantiation Points

More appropriate initialization points override activation hooks. The admin_init hook efficiently limits scope to the admin dashboard when applicable. Later hooks like wp allow explicitly narrow targeting to specific plugin features only when required.

Instantiating Classes for Frontend Usage

For frontend logic, key considerations when initializing classes include hook selection and avoidance of duplicate redundant instances.

Hook to wp or template_redirect

Early frontend hooks like wp allow class instantiation cleanly tied to theme setup logic. The later template_redirect hook activates classes only when the main request passes necessity checks, avoiding premature load.

Watch Out for Loops and Duplicates

As class instantiation triggers at both parent and child theme levels, implementing checks to avoid duplicate initialization is wise. Additionally, hooks triggered multiple times through loops require special attention to prevent multiplied instances.

Example Code

Reviewing example code highlights the impact of different class instantiation strategies:

Bad Practice

// On file load
$logger = new Logger(); 

// On plugins_loaded 
$api = new ExternalApi(); 

// On init
$adminSettings = new AdminSettings();

This code prematurely instantiates key classes globally regardless of actual usage. It leads to wasted memory, hidden dependencies, and unexpected behavior as code changes.

Good Practice

// Logger class 
function get_logger() {

  static $logger = null;
  
  if (is_null($logger)) {
    $logger = new Logger();
  }

  return $logger; 
}

// On admin_init
$adminSettings = new AdminSettings();

// On wp 
$api = new ExternalApi();

Here usage is deferred until explicitly required, preventing unnecessary resource usage. The singleton logger avoids duplicated instances, while other classes initialize locally only when applicable through hooks and scopes.

Singletons vs Multiple Instances

Singletons conserve memory by limiting classes to one global instance across code. This works well for centralized resources like loggers, but often multiple instances better serve features handling unique data flows like API requests.

Summary

In summary, guidelines for smart class instantiation in WordPress include:

  • Initialize only when explicitly required by code logic
  • Leverage hooks and scoping for targeted initialization points
  • Use dependency injection over reliance on global variables
  • Implement deferred instantiation for expensive resources

Following these best practices avoids the pitfalls of premature initialization like wasted resources and breakage while promoting robust, scalable plugin architecture through minimal impact and loose couplings.

Leave a Reply

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