This library allows you to implement dependency injection design pattern in your WordPress plugin or theme. It provides a simple and easy-to-use interface to manage dependencies and hook callbacks.
- Reliable - Powered by PHP-DI, a mature and feature-rich dependency injection container.
- Interoperable - Provides PSR-11 compliant container interface.
- Easy to use - Reduces the boilerplate code required to manage dependencies and hook callbacks.
- Customizable - Allows various configuration options to customize the container behavior.
- Flexible - Enables advanced hook callback mechanisms.
- Fast - Dependencies are resolved only when needed, and the container can be compiled for better performance.
You can install this package via composer:
composer require x-wp/di
Tip
We recommend using the automattic/jetpack-autoloader
with this package to prevent autoloading issues.
Below is a simple example to demonstrate how to use this library in your plugin or theme.
You will need a class which will be used as the entry point for your plugin/theme. This class must have a #[Module]
attribute to define the container configuration.
<?php
use XWP\DI\Decorators\Module;
#[Module(
container: 'my-plugin', // Unique identifier for the container
hook: 'plugins_loaded', // Hook to initialize the a
priority: 10, // Hook priority
imports: array(), // List of classnames imported by this module
handlers: array(), // List of classnames which are used as handlers
)]
class My_Plugin {
/**
* Returns the PHP-DI container definition.
*
* @see https://php-di.org/doc/php-definitions.html
*
* @return array<string,mixed>
*/
public static function configure(): array {
return array(
'my.def' => \DI\value('my value'),
);
}
}
After defining the module, you can create the application using the xwp_create_app
function.
<?php
xwp_create_app(
array(
'id' => 'my-plugin',
'module' => My_Plugin::class,
'compile' => false,
);
);
Handler is any class which is annotated with a #[Handler]
attribute. Class methods can be annotated with #[Action]
or #[Filter]
attributes to define hook callbacks.
<?php
use XWP\DI\Decorators\Action;
use XWP\DI\Decorators\Filter;
use XWP\DI\Decorators\Handler;
#[Handler(
tag: 'init',
priority: 20,
container: 'my-plugin',
context: Handler::CTX_FRONTEND,
)]
class My_Handler {
#[Filter( tag: 'body_class', priority: 10 )]
public function change_body_class( array $classes ): array {
$classes[] = 'my-class';
return $classes;
}
#[Action( tag: 'wp_enqueue_scripts', priority: 10 )]
public function enqueue_scripts(): void {
wp_enqueue_script('my-script', 'path/to/my-script.js', array(), '1.0', true);
}
}
For more information, please refer to the official documentation.