magento2中的Plugin--before方法详解
  • Magento
  • 2023-07-23 14:22:06
  • 29899 阅读

magento2的插件机制允许我们对指定方法运行之前或者之后对该方法进行动态修改,包括对方法的参数、返回值等。

本篇文章我们为大家介绍一下magento2中的Plugin机制中的before方法。

before插件,顾名思义,在观察到的方法之前运行。在编写before plugin时,有几个要点需要记住:

before关键字被附加到observedinstance方法中。如果观察到的方法被调用getSomeValue,那么插件方法被调用beforeGetSomeValue。

before-plugin方法的第一个参数始终是观察到的实例类型,通常缩写为$subject或直接由类类型缩写——在我们的示例中是$processor。

为了提高可读性,我们可以对其进行类型转换。插件方法的所有其他参数必须与观察到的方法的参数匹配。

插件方法必须返回一个数组,该数组的参数类型和数量与观察到的方法的输入参数相同。让我们来看看Magento在插件实现之前的一个,

即<Magento_DIR>模块支付/etc/frontend/di.xml文件中指定的一个:

<type name="Magento\Checkout\Block\Checkout\LayoutProcessor">
    <plugin name="ProcessPaymentConfiguration"             type="Magento\Payment\Plugin\PaymentConfigurationProcess"/>
</type>

此插件的原始目标方法是Magento\Checkout\Plock\Checkout\LayoutProcessor类的处理方法:

public function process($jsLayout) {    // The rest of the code...    return $jsLayout;}

before插件的实现是通过Magento\Payment\plugin\PaymentConfigurationProcess类的beforeProcess方法提供的,如以下部分示例所示:

public function beforeProcess(
\Magento\ Checkout\ Block\ Checkout\ LayoutProcessor $processor, $jsLayout
) { // The rest of the code...    return [$jsLayout];}