Wp plugin architecture

From Lonsdale201/wp-agent-skills · View interactive version

Wp plugin architecture is an AI agent skill from the GitHub repository Lonsdale201/wp-agent-skills. Designs and reviews the internal architecture of a WordPress plugin — `src/` folder layout, Composer PSR-4 one-class-per-file discipline, PascalCase filenames matching class names, no `class-*.php` legacy layout, Schema/Constants placement, composition-root vs singleton decisions, conditional asset

How to use this skill

Skill file

WordPress plugin: internal architecture

How the plugin organizes itself inside src/ once the bootstrap (see wp-plugin-bootstrap) and lifecycle (see wp-plugin-lifecycle) are in place. The bootstrap is the launcher; this skill is the engine layout.

Use src/ as the default PSR-4 root for new plugins. Treat includes/ and class-*.php filenames as legacy patterns to audit or migrate, not as a scaffold target.

Out of scope: bootstrap-file content, activation / deactivation / uninstall, cron specifics, REST endpoint design — covered by sibling skills.

When to use this skill

Trigger when ANY of the following is true:

Folder layout — by-type or by-feature

Choose either by-type for a small cohesive plugin or by-feature when several

domains evolve independently. Do not mix both schemes opportunistically.

Across both styles, keep one class per PascalCase file and mirror the PSR-4

namespace path. Read references/layout-and-review-examples.md for both trees,

migration signals, and a review comparison.

Composer mapping:

{
    "autoload": {
        "psr-4": {
            "MyPlugin\\": "src/"
        }
    }
}

Centralization — `Schema` / `Constants` is non-negotiable

Every string that appears more than once — meta key, option name, custom hook name, cron event name, CPT slug, capability slug, transient prefix — lives in one place. Three patterns that all work:

Class const on the feature class

class UsageTracker {
    public const OPTION_PREFIX = 'myplugin_usage_';

    public static function current_month_key(): string {
        return self::OPTION_PREFIX . gmdate( 'Y_m' );
    }
}

When the constant logically belongs to one feature, define it there. Cleanest scope.

Dedicated `Schema` class for cross-feature constants

namespace MyPlugin;

final class Schema {
    public const META_FORM_SETTINGS = '_myplugin_form_settings';
    public const OPTION_GLOBAL      = 'myplugin_global_settings';
    public const CPT_LOG            = 'myplugin_log';
    public const CRON_DAILY         = 'myplugin_daily_cleanup';
    public const HOOK_BEFORE_REQUEST = 'myplugin/before_request';

    private function __construct() {} // not instantiable
}

Then everywhere: Schema::META_FORM_SETTINGS instead of the literal string. Renaming becomes one-line; typos become impossible (the class autoloader catches them).

PHP 8.1+ enum for typed value sets

For a fixed value set (failure modes, output types, etc.), use enums only when

the plugin's declared minimum PHP version is 8.1 or higher:

enum FailureMode: string {
    case Halt        = 'halt';
    case Permissive  = 'permissive';
    case Restrictive = 'restrictive';
}

// Then instead of error-prone string parsing:
$mode = FailureMode::tryFrom( $raw ) ?? FailureMode::Halt;

Type-safe, enumerable, documents itself.

For PHP 7.4 / 8.0-compatible plugins, use class constants plus explicit

validation instead:

final class FailureMode {
    public const HALT        = 'halt';
    public const PERMISSIVE  = 'permissive';
    public const RESTRICTIVE = 'restrictive';

    public static function normalize( string $raw ): string {
        return in_array( $raw, self::all(), true ) ? $raw : self::HALT;
    }

    public static function all(): array {
        return array( self::HALT, self::PERMISSIVE, self::RESTRICTIVE );
    }
}

The hard rule: if you find yourself typing the same magic string in two files, that's the moment to centralize. The wrong direction is "I'll only have it in two places, no need yet" — git grep next year proves the lie.

Singleton discipline — composition root yes, everything else no

The Plugin class is often the composition root: one object wires services,

hooks, controllers, settings, and integrations after bootstrap. It MAY expose a

small instance() helper when the surrounding plugin style already uses that

pattern, but a singleton is not required. A plain new Plugin(...)->register()

from the bootstrap is usually easier to test.

Beyond the composition root, don't make everything a singleton by reflex.

The price of singleton-everywhere: tests can't substitute mocks, dependencies become hidden, and you accumulate a Plugin::instance()->get_storage_manager()->get_provider_registry() getter chain that nobody can refactor.

When in doubt: write the class as a regular class. Promote to singleton only when there's a concrete reason (genuine global state, expensive lazy initialization shared across many call sites, or compatibility with an existing plugin API).

Asset enqueueing — conditional, on the right hook

The wrong way: enqueue every script and stylesheet on every page load via wp_enqueue_scripts. The right way:

  1. Pick the right hook for the right context. Verified in WP source:
  1. Gate by context inside the hook callback:

```php

add_action( 'admin_enqueue_scripts', static function ( string $hook_suffix ): void {

// Only on the plugin's own settings page

if ( $hook_suffix !== 'settings_page_myplugin' ) {

return;

}

wp_enqueue_script( /* ... */ );

} );

```

For frontend, gate by is_singular() / has_block( 'myplugin/contact' ) / specific shortcodes.

  1. Always declare dependencies — even ones that "feel obvious". wp-element, wp-components, wp-i18n, wp-hooks, your own scripts. Without proper deps the script may run before the dependency is defined and break.
  1. Cache-bust deterministically. Two valid patterns:
  1. $args array since WP 6.3 — the 5th parameter overloads from a boolean $in_footer to an array supporting strategy ('defer' or 'async'), in_footer, and fetchpriority (since 6.9). Use 'strategy' => 'defer' instead of jQuery-era ready-handlers when feasible.

`wp_add_inline_script` preferred over `wp_localize_script` for new code

wp_localize_script (since 2.2; defined in wp-includes/functions.wp-scripts.php) creates a JavaScript object from an associative array. It still works, but for arbitrary runtime config it is a legacy-shaped helper: it requires an array payload and creates a top-level global. Use wp_set_script_translations() for JavaScript translations.

wp_add_inline_script (since 4.5; defined in wp-includes/functions.wp-scripts.php) is the modern path: any JS string, before or after the registered script. Use wp_json_encode() to serialize structured data:

wp_add_inline_script(
    'myplugin-editor',
    'window.MyPluginConfig = ' . wp_json_encode( array(
        'restUrl' => esc_url_raw( rest_url( 'myplugin/v1/' ) ),
        'nonce'   => wp_create_nonce( 'wp_rest' ),
    ) ) . ';',
    'before'
);

Both functions still work; for a new plugin, default to wp_add_inline_script

for configuration and wp_set_script_translations() for script translations.

Hook naming — prefix everything

Custom action / filter hooks the plugin emits (so other developers can wire into your behavior) follow ONE naming convention, picked once and never deviated from:

// Slash-separated (common in modern plugins and integrations)
do_action( 'myplugin/before_request', $payload );
apply_filters( 'myplugin/api_response', $response, $request );

// Underscore-separated (classic; common in WordPress core)
do_action( 'myplugin_before_request', $payload );

Both are common in the ecosystem, but WordPress core itself mostly uses

underscore-separated hook names such as pre_get_posts and

rest_pre_serve_request. If the project uses WPCS rules that discourage slashes

in hook names, pick underscores. The hard rule: **prefix every custom hook with

the plugin slug**. do_action( 'before_request', ... ) is a foot-gun —

collisions with other plugins are guaranteed at scale.

When you DO emit a custom hook, give it a docblock right above:

/**
 * Fires before the AI request is sent.
 *
 * @since 1.0.0
 *
 * @param array $payload The request payload (mutable downstream).
 */
do_action( 'myplugin/before_request', $payload );

@since lets users pin their integration; AI assistants reading the source rely on these to suggest correct hooks.

Critical rules

Common mistakes

Read references/layout-and-review-examples.md for wrong/right examples of

magic strings, unconditional assets, reflexive singletons, bare hooks, and

legacy class filenames.

Cross-references

What this skill does NOT cover

References

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.