Plugin execution order by weight

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

 

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.