The before plugin, as its name suggests, runs before the observed method.
When writing a before plugin, there are a few key points to remember:
- The before keyword is appended to the observed instance method. If the observed method is called getSomeValue, then the plugin method is called beforeGetSomeValue.
- The first parameter of the before plugin method is always the observed instance type, often abbreviated as $subject or directly by the class type – which is $processor in our example. We can typecast it for greater readability.
- All other parameters of the plugin method must match the parameters of the observed method.
- The plugin method must return an array with the same type and number of parameters as the observed method's input parameters.
Let's take a look at one of Magento's before plugin implementations, the one specified in the <MAGENTO_DIR>module-payment/etc/frontend/di.xml file:
<type name="MagentoCheckoutBlockCheckoutLayoutProcessor">
<plugin name="ProcessPaymentConfiguration"
type="MagentoPaymentPluginPaymentConfigurationProcess"/>
</type>
The original method this plugin is targeting is the process method of the MagentoCheckoutBlockCheckoutLayoutProcessor class:
public function process($jsLayout) {
// The rest of the code...
return $jsLayout;
}
The implementation of the before plugin is provided via the beforeProcess method of the MagentoPaymentPluginPaymentConfigurationProcess class, as per the following partial example:
public function beforeProcess(
MagentoCheckoutBlockCheckoutLayoutProcessor $processor,
$jsLayout) {
// The rest of the code...
return [$jsLayout];
}