When we create our custom plugins in Drupal 8, we sometimes need them to be executed in a particular order.
For example, if we would run a text analyzer that finds frequencies of words and frequent phrases, we would first want to run the HTML filter which strips out all tags and/or special characters and then execute the text analyzer. Whatever the reason be, Drupal 8 default plugin manager Drupal\Core\Plugin\DefaultPluginManager has a method called getDefinitions.
This method returns all registered plugin type definitions. We can take advantage of this method to return plugin type definitions in the desired order. Let's try to demonstrate this on a minimalistic code example.
The plugin needs to support the weight annotation which value is an integer (lower integer has a higher priority).
namespace Drupal\mymodule\Annotation;
use Drupal\Component\Annotation\Plugin;
/**
* My plugin annotation.
*
* @Annotation
*/
class MyPlugin extends Plugin {
/**
* Plugin weight.
*
* @var int
*/
public $weight;
}
Next, we use Drupal\Component\Utility\SortArray as PHP user-defined array sorting function callback for uasort.
namespace Drupal\mymodule;
use Drupal\Component\Utility\SortArray;
use Drupal\Core\Plugin\DefaultPluginManager;
/**
* My custom plugin manager.
*/
class MyPluginManager extends DefaultPluginManager {
//
// Your plugin manager constructor and other methods/properties.
//
/**
* {@inheritdoc}
*/
public function getDefinitions() {
$definitions = parent::getDefinitions();
uasort($definitions, [SortArray::class, 'sortByWeightElement']);
return $definitions;
}
}
And we are done.
Now code that will get the plugin definitions will get back plugins order by weight and should run them in the order defined by weight as in the following code example:
$definitions = $this->myPluginManager->getDefinitions();
foreach ($definitions as $pluginId => $definition) {
$this->searchQueryPluginManager
->createInstance($pluginId)
->execute($someData);
}
Resources
- Drupal 8 sort by weight method https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Component%21Utility%21SortArray.php/function/SortArray%3A%3AsortByWeightElement/8.9.x
- PHP uasort function https://www.php.net/manual/en/function.uasort.php
Add new comment