Swapping out classes in plugins

In drupal 8 plugins are everywhere, so to get most out of them you will sometimes want to alter them. If you look at definitions of each plugin manager, you will see that all of them have something specific in their constructors, it is the line below


which makes it possible to alter info about plugins they manage, alterInfo derives from this class defaultPluginManager method and it is quite useful when you want to change some plugin. Let say you want to use different class for specific plugin, for example we want to change the code we use to define checkout panes in drupal commerce. What we would do is override "review pane" which has its own class defined in following namespace Drupal\commerce_checkout\Plugin\Commerce\CheckoutPane as class Review. 

Next we will use hook_plugin_alter to do this, as this pane is part of the CheckoutPaneManager plugin where it has its alter defined as


This alter needs to go into custom module in .module file, use this info to call alter and define swapp class as

function custom_module_commerce_checkout_pane_info_alter(array &$info) {
  $info['review']['class'] = CustomReview::class;
  $info['review']['provider'] = 'custom_module';

where first line is path to the new class and second is module where this class is located (don't forget to use proper namespaces in .module file).

Resulting in drupal using this new class instead of the old one for that particular pane, which is keyed in array as "review". You could also extend original class, use its form as parent and then add extra code you need.