VOOZH about

URL: https://deepwiki.com/auth0/wordpress/3.2-plugin-initialization-and-bootstrap

⇱ Plugin Initialization and Bootstrap | auth0/wordpress | DeepWiki


Loading...
Menu

Plugin Initialization and Bootstrap

This document describes the complete lifecycle of the Auth0 WordPress plugin from activation through runtime initialization, including the bootstrap process, singleton pattern implementation, dependency loading, SDK configuration, and hook registration.

For information about the authentication flow after initialization, see Authentication Flow. For details about configuration management, see Configuration Management.


Overview

The plugin initialization process follows a structured lifecycle consisting of three distinct phases:

  1. Activation Phase: Cryptographic secrets are generated and stored in wp_options
  2. Bootstrap Phase: Dependencies are loaded and the wpAuth0() singleton function is defined
  3. Runtime Phase: The Plugin instance is created, SDK is configured, and actions/filters are registered with WordPress

The entry point is wpAuth0.php, which WordPress loads as the main plugin file. This file orchestrates the entire initialization sequence and provides a global accessor function for plugin functionality.

Sources: wpAuth0.php1-90 src/Plugin.php21-330


Activation Phase

When the plugin is activated, WordPress triggers the activation hook registered in wpAuth0.php. This hook performs a critical initialization task: generating cryptographic secrets if they don't already exist.

Secret Generation

The activation hook checks and generates three distinct secrets stored in wp_options:

Option KeyPurposeSecret Length
auth0_cookies['secret']Encrypts session cookies128 hex characters (64 bytes)
auth0_backchannel_logout['secret']Authenticates back-channel logout requests128 hex characters (64 bytes)
auth0_authentication['fallback_secret']Enables WordPress fallback login128 hex characters (64 bytes)

Each secret is generated using random_bytes(64) and converted to hexadecimal format using bin2hex(). The secrets are only generated if the corresponding option doesn't exist or is empty, preserving existing secrets during plugin updates.


Diagram: Plugin Activation Secret Generation Flow

Sources: wpAuth0.php40-67


Dependency Loading and Autoloading

After activation, when WordPress loads the plugin, the first operation is loading PHP dependencies through Composer's autoloader.

Autoloader Selection

The plugin supports two autoloader configurations with a preference for scoped builds:


Diagram: Composer Autoloader Resolution

The scoped autoloader (scoper-autoload.php) is preferred because it contains dependencies that have been namespace-prefixed to Auth0\WordPress\Vendor\* to prevent conflicts with other plugins. The regular autoloader is a fallback for development environments.

Once loaded, the autoloader enables PSR-4 autoloading for the Auth0\WordPress\ namespace, mapped to the src/ directory.

Sources: wpAuth0.php34-38


Singleton Pattern: The wpAuth0() Function

The plugin implements a singleton pattern through the wpAuth0() global function, which serves as the primary access point to plugin functionality.

Function Signature and Implementation


The function accepts three optional parameters to support dependency injection for testing, but in production use, all parameters are null.

Singleton Mechanics


Diagram: wpAuth0() Singleton Resolution Logic

The null coalescing assignment operator (??=) at line 86 ensures the static variable is only assigned once: $instance ??= $instance ?? $plugin ?? new Plugin($sdk, $configuration);

This creates a single Plugin instance shared across all calls, preventing duplicate initialization and ensuring consistent state.

Sources: wpAuth0.php79-89


Plugin Class Construction

The Plugin class constructor accepts two optional parameters and stores them as private properties:


During normal operation, both parameters are null, triggering lazy initialization when the SDK or configuration is first accessed.

Class Constants

The Plugin class defines two critical constants that list action and filter classes:

ConstantClassesPurpose
ACTIONSAuthenticationActions, ConfigurationActions, SyncActions, ToolsActions, UpdatesActionsClasses that hook into WordPress actions
FILTERSAuthenticationFiltersClasses that hook into WordPress filters

Sources: src/Plugin.php21-43


Runtime Initialization: Plugin::run()

After the wpAuth0() function returns the singleton instance, the main plugin file immediately calls run() to begin the initialization process.


Diagram: Plugin Runtime Initialization Sequence

The run() method performs two main operations:

  1. Filter Registration: Iterates through self::FILTERS and calls register() on each instantiated class
  2. Action Registration: Iterates through self::ACTIONS and calls register() on each instantiated class

Each class instance is obtained through getClassInstance(), which maintains a registry to ensure singleton behavior per class type.

Sources: src/Plugin.php224-245 src/Plugin.php86-93


Action and Filter Registration

Each action and filter class extends the Base abstract class, which provides the registration infrastructure through the register() method.

Registry Pattern

Action classes define a $registry property mapping WordPress hook names to method names:


The register() method iterates through this registry and calls addAction() for each entry.

Hook Registration Flow


Diagram: Action Registration Flow from Registry to WordPress Hooks

Method Specification Formats

The registry supports two formats:

  1. Simple String: 'hook_name' => 'methodName' - Uses default priority (10) and 1 argument
  2. Array with Arguments: 'hook_name' => ['methodName', 3] - Uses default priority (10) and specified argument count (3)

Priority can be customized through environment constants following the pattern AUTH0_ACTION_PRIORITY_{HOOK_NAME}.

Sources: src/Actions/Base.php16-122 src/Hooks.php1-63


SDK Configuration Building

The Auth0 SDK requires a SdkConfiguration object, which the plugin builds by reading settings from wp_options.

Configuration Import Process


Diagram: SDK Configuration and Initialization Flow

Configuration Strategies

The plugin uses different initialization strategies based on the execution context:

ContextStrategySession StorageUse Case
Normal RequestSTRATEGY_REGULAREnabledFull authentication flow with sessions
WP_Cron JobSTRATEGY_NONEDisabledBackground sync tasks without user sessions

The cron context is detected by checking if the DOING_CRON constant is defined.

Option Reading Pattern

Configuration values are read from wp_options using the pattern auth0_{group} where the value is an array containing settings for that group:


The Plugin::getOption() method provides a helper for reading nested values:


PSR-18/17 Factory Integration

The configuration uses the Factory class to obtain PSR-compliant HTTP implementations:

  • Factory::getRequestFactory() - PSR-17 RequestFactoryInterface
  • Factory::getResponseFactory() - PSR-17 ResponseFactoryInterface
  • Factory::getStreamFactory() - PSR-17 StreamFactoryInterface
  • Factory::getClient() - PSR-18 ClientInterface

These are provided by the site's PSR implementation (e.g., Guzzle, Symfony HTTP Client).

Sources: src/Plugin.php164-169 src/Plugin.php274-329 src/Plugin.php113-159


Database Table Creation

Custom database tables are created on-demand rather than during activation. This lazy creation pattern prevents activation failures and ensures tables exist when needed.

Table Creation Trigger

Action classes call prepDatabase() before accessing custom tables:


This method uses both WordPress object cache and transients to ensure table existence is only checked once per 30 minutes (1800 seconds).

Custom Tables

The plugin uses two custom tables:

Table NameConstantPurposeSchema Definition
{prefix}auth0_accountsDatabase::CONST_TABLE_ACCOUNTSMaps WordPress user IDs to Auth0 connection identifiers (sub claims)src/Database.php101-119
{prefix}auth0_syncDatabase::CONST_TABLE_SYNCEvent queue for background synchronization taskssrc/Database.php121-141

The Database class provides an abstraction layer over WordPress's $wpdb global with methods like:

  • createTable(string $table) - Creates table if not exists
  • insertRow(string $table, array $data, array $formats) - Inserts a row
  • selectRow(string $select, string $from, string $query, array $args) - Selects single row
  • selectResults(string $select, string $from, string $query, array $args) - Selects multiple rows
  • deleteRow(string $table, array $where, array $format) - Deletes rows

Sources: src/Actions/Authentication.php645-658 src/Database.php9-149


Complete Initialization Sequence

The following diagram shows the complete initialization flow from plugin file load through action registration:


Diagram: Complete Plugin Initialization Sequence

Sources: wpAuth0.php1-90 src/Plugin.php21-330 src/Actions/Base.php16-122


Key Initialization Points

The initialization process has several key characteristics:

  1. Lazy Loading: The SDK and configuration are only created when first accessed, not during run()
  2. Singleton Pattern: Both the Plugin instance and individual action class instances are singletons
  3. On-Demand Tables: Database tables are created when first accessed, not during activation
  4. Context-Aware Configuration: Different SDK strategies for normal requests vs. cron jobs
  5. Secret Persistence: Cryptographic secrets are generated once during activation and reused
  6. Scope Isolation: Dependencies are namespace-prefixed to prevent conflicts with other plugins

This architecture ensures efficient initialization, prevents conflicts, and provides flexibility for different execution contexts.

Sources: wpAuth0.php1-90 src/Plugin.php21-330 src/Actions/Authentication.php645-658