Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 68 ยท Plugins

Plugin Structure and Object-Oriented Plugins

Organize a WordPress plugin with a clean folder layout, namespaced classes, an autoloader, dependency injection and bootstrapping on plugins_loaded.

A one-file plugin is fine for ten lines of code. Once a plugin grows to a settings page, a custom post type and some REST routes, a single file becomes a tangle. The cure is the same as in any PHP project: split the code into classes, give each class its own file, and let an autoloader include files on demand. This lesson shows a folder layout that scales, how namespaces and autoloading fit WordPress, the trade-offs between singletons and dependency injection, and where to start the whole thing.

You will use the PHP features from Namespaces and Autoloading and Composer. If you have not written a plugin yet, read Your First Plugin first.

A folder layout that scales

There is no mandatory structure, but most well-kept plugins converge on something like this:

TEXT
northwind-notice/
  northwind-notice.php        <- header, constants, bootstrap only
  uninstall.php
  composer.json               <- optional, for autoloading
  src/
    Plugin.php                <- wires everything together
    Admin/
      Settings_Page.php
    Content/
      Notice_Filter.php
  templates/
    notice.php
  assets/
    css/
    js/
  languages/

Keep these rules in mind:

  • The main file contains the header comment, the ABSPATH guard, a few constants and the line that starts the plugin. No business logic.
  • src/ holds classes, one class per file, with the file path mirroring the namespace.
  • templates/ holds markup, so classes do not build HTML out of string concatenation.
  • Anything that must run at the moment a user clicks "Delete" goes in uninstall.php, covered in Activation, Deactivation and Uninstall.

Namespaces and class names

Namespaces give your classes unique names without a long prefix on each. Choose one root namespace for the plugin, usually a vendor and a project: Northwind\Notice. The class Northwind\Notice\Admin\Settings_Page then lives in src/Admin/Settings_Page.php.

Namespaces do not cover everything. Hook names, option names, post meta keys, script handles and shortcode tags are plain strings that all plugins share, so they still need a prefix like nwn_. Functions and classes in the global namespace need a prefix too, which is why many plugins that use a namespace have almost no global functions at all.

The WordPress coding standards name class files class-settings-page.php, which an autoloader can support too; many modern plugins prefer PSR-4 names such as Settings_Page.php with Composer. Pick one convention and stick to it.

Autoloading

An autoloader is a function PHP calls when code mentions a class that is not defined yet. It maps the class name to a file path and includes that file. There are two usual routes:

Composer. Add a PSR-4 map to composer.json and require the generated file once:

JSON
{
	"autoload": {
		"psr-4": { "Northwind\\Notice\\": "src/" }
	}
}
PHP
require_once __DIR__ . '/vendor/autoload.php';

Composer is the best choice when you also use third-party libraries. You must ship the vendor/ folder with the released plugin because the site owner will not run Composer.

Your own spl_autoload_register. For small plugins with no dependencies, a dozen lines do the job:

PHP
spl_autoload_register( function ( $class ) {
	$prefix = 'Northwind\\Notice\\';
	if ( 0 !== strpos( $class, $prefix ) ) {
		return;
	}
	$relative = substr( $class, strlen( $prefix ) );
	$file     = __DIR__ . '/src/' . str_replace( '\\', '/', $relative ) . '.php';
	if ( is_readable( $file ) ) {
		require $file;
	}
} );

The first lines make sure the autoloader ignores classes that belong to somebody else. Only classes that actually get used are loaded, so a large plugin pays for the code it runs on each request and no more.

Bootstrapping on plugins_loaded

Plugin files load early, before the theme and before most of WordPress is ready. The main file should therefore do almost nothing at load time: set up the autoloader, then hand over to a Plugin class on a hook.

PHP
<?php
/**
 * Plugin Name: Northwind Notice
 * Version:     1.0.0
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

define( 'NWN_VERSION', '1.0.0' );
define( 'NWN_FILE', __FILE__ );

require_once __DIR__ . '/vendor/autoload.php';

add_action( 'plugins_loaded', function () {
	( new Northwind\Notice\Plugin() )->register();
} );

plugins_loaded fires once all active plugins are loaded. Starting there lets your plugin cooperate with others (it can check whether another plugin's class exists). Plugin::register() then only adds hooks, for example to init and admin_menu; the real work happens when those hooks fire. A constructor that does real work, such as querying the database, is a common source of slow, hard-to-test plugins.

flowchart TB
    F["northwind-notice.php"] --> A["Autoloader registered"]
    A --> PL["plugins_loaded"]
    PL --> P["Plugin::register()"]
    P --> H1["add_action init<br/>Notice_Filter"]
    P --> H2["add_action admin_menu<br/>Settings_Page"]

The main file wires the autoloader and one start-up hook; the Plugin class registers the rest.

Singleton or dependency injection?

Many WordPress plugins use the singleton pattern: a class keeps a static instance and hands it out through Plugin::instance(). It is easy to write, and you can reach the object from anywhere. The costs are real, though. Singletons are global state in disguise, they make tests awkward because the instance survives between tests, and they hide which classes depend on which.

Dependency injection is the alternative: a class receives what it needs as constructor arguments. The Plugin class creates the objects and passes them in.

PHP
final class Plugin {
	public function register() {
		$options = new Options( 'nwn_options' );
		$filter  = new Notice_Filter( $options );
		$filter->register();
	}
}

Notice_Filter now declares its dependency on Options openly, and a test can pass a fake Options. For a plugin of any size, prefer injection and create everything in one place, the composition root. A full container library is optional and usually unnecessary at plugin scale.

One more rule: an object must keep hooks to its own methods registered through [ $this, 'method' ]. If a hook callback needs to be removable later by other code, keep the object accessible, because removing a class-method hook needs the same instance, as you will see in Priorities, Order and Removing Hooks.

Seeing it work

Real autoloading includes files from disk. The stand-in below cannot create files, so it keeps the "files" in a PHP array and its autoloader evals the stored source. That is a teaching trick only; never eval code in a real plugin. What it shows is real: namespaces mapped to paths, classes loaded lazily, dependency injection, and a Plugin that only registers hooks when plugins_loaded fires.

PHP A namespaced mini plugin with an autoloader

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Check the order in the output. Nothing is loaded before the start-up hook. After it, only the classes the code touched were loaded, and each file was pulled in at the moment of first use.

Practical tips

  • Keep the main file under about thirty lines.
  • Put constants such as the version and the plugin URL in the main file; classes read them, they do not define them.
  • Use plugin_dir_path( __FILE__ ) and plugin_dir_url( __FILE__ ) instead of hard-coded paths.
  • Separate registration (cheap, always runs) from work (runs only when its hook fires).
  • Do not scatter global $wpdb through your classes; inject what a class needs.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What should the main plugin file contain?

    Keep the main file small: header, guard, constants, autoloader and the line that starts the plugin.
  2. 2. Why do option names and hook names still need a prefix even if the plugin uses namespaces?

    Namespaces only qualify classes, functions and constants. Options, hooks, handles and meta keys are plain strings in a shared space.
  3. 3. When does the plugins_loaded action fire?

    It fires once every active plugin file has been included, so plugins can safely check for each other.
  4. 4. What is a main drawback of the singleton pattern in plugins?

    A singleton is reachable from anywhere, so classes hide what they depend on and tests share one instance.
  5. 5. What does a PSR-4 autoloader do?

    The namespace prefix maps to a folder, and the remaining class path maps to a file, loaded lazily on first use.

Summary

  • Keep the main file tiny; put classes in src/, markup in templates/ and assets in assets/.
  • Use one root namespace and a PSR-4 layout; still prefix option, hook, handle and meta names.
  • Autoload with Composer (ship vendor/) or a short spl_autoload_register function.
  • Start on plugins_loaded, where Plugin::register() only adds hooks.
  • Prefer constructor injection over singletons; build objects in one composition root.
  • The TryIt uses eval as a stand-in for require; never do that in a real plugin.

Next up: Activation, Deactivation and Uninstall.