Skip to main content

Context

Context class is the central runtime component in WP-Node. It initializes and manages core components such as configuration, roles, hooks, current user, and utilities.


Overview

  • Dependency Management: Uses the Components system for resolving internal services.
  • User & Role Setup: Handles role assignment and anonymous user initialization.
  • Multisite Support: Switches blog/site context automatically when multisite is enabled.
  • Environment-aware: Accepts env flag to isolate or differentiate application contexts.
  • Cloneable: Can be duplicated via the clone() method for isolated operations.

Properties

  • config: Instance of the configuration passed to the context.
  • hooks: Instance of registered hook handlers (filter/action).
  • current: Handles the current user and site state.
  • roles, utils, vars, options, logger: Pre-wired internal modules.
  • env: Returns the current environment (e.g. "local").

Methods

getInstance(config, { env, hooks, installing? })

Creates and fully initializes a new Context instance. Sets up the current site/user and fires the core_init hook.

Note: This method is typically not called directly. Use Application.getContext(env) instead, which handles the proper initialization and configuration setup.

clone()

Creates a fresh copy of the context with the same environment and configuration:

const cloned = await context.clone();

Multisite Behavior

If multisite is enabled, getInstance will automatically switch to the configured default site and blog ID:

if (config.multisite.enabled) {
await context.current.switchSite(
config.multisite.defaultSiteId,
config.multisite.defaultBlogId
);
}

If not, it simply sets default user roles.


Error Handling

During getInstance(), errors in role resolution are handled gracefully—especially during installation. Default roles are applied when needed:

context.current.setDefaultUserRoles();

To avoid install-time crashes:

if (!installing) {
console.warn("Failed to initialize the Current component.", e);
}