drupal / plugin_topsort
A mechanism for ordering plugin definitions using a directed acyclic graph.
Requires
- drupal/core-plugin: ^10 || ^11 || ^12
- marcj/topsort: ^2.0
README
A mechanism for ordering plugin definitions using a directed acyclic graph.
It is intended for developers who are writing custom plugins, where the plugin definitions need to be "in order". Typically, these are plugins which transform data in some way, where the order of the transformations matters.
Usage
1. Add before/after properties to plugin definitions
A directed acyclic graph can be defined by way of before and after
properties in the plugin definition:
#[\Attribute(\Attribute::TARGET_CLASS)]
final class MyPlugin extends Plugin {
public function __construct(
string $id,
public readonly array $before = [],
public readonly array $after = [],
?string $deriver = NULL,
) {
parent::__construct($id, $deriver);
}
}
How to interpret these properties:
- A plugin's
beforeproperty can be thought of as "this plugin must run before the listed plugins". - A plugin's
afterproperty can be thought of as "this plugin must run after the listed plugins".
For example, the order of the following plugins may be enforced like this:
#[MyPlugin('first', before: ['second'])]
#[MyPlugin('second')]
#[MyPlugin('third', after: ['second'])]
You do not need to specify both before and after constraints to form
a dependency - either will suffice.
A LogicException is thrown if the constraints imply a circular dependency.
2. Add the trait to the plugin manager
- Use the
PluginManagerTopologicalSortTraitin your plugin manager:
use \Drupal\plugin_top_sort\PluginManagerTopologicalSortTrait;
class MyPluginManager extends DefaultPluginManager {
use PluginManagerTopologicalSortTrait;
...
}
The trait provides a findDefinitions() function that looks like this:
public function findDefinitions(): array {
$definitions = parent::findDefinitions();
// sort definitions
return $definitions;
}
Sorting happens after discovery, and after any alter hook has been called.
3. Plugin manager behavior.
The array returned by the plugin manager's getDefinitions() function
will be sorted in a way that respects the directed acyclic graph.