当前位置: 技术文章>> magento2中的Plugin机制--around方法详解

文章标题:magento2中的Plugin机制--around方法详解
  • 文章分类: Magento
  • 14180 阅读
系统学习magento二次开发,推荐小册:《Magento中文全栈二次开发 》

本小册面向Magento2以上版本,书代码及示例兼容magento2.0-2.4版本。涵盖了magento前端开发,后端开发,magento2主题,magento2重写,magento2 layout,magento2控制器,magento2 block等相关内容,带领您成为magento开发技术专家。


around插件围绕观察到的方法运行,使我们能够在原始方法调用前后运行一些代码。这是一个非常强大的概念,因为我们可以更改传入的参数以及函数的返回值。

在编写around插件时,有几个关键点需要记住:

传递给插件的第一个参数是观察到的类型实例。进入插件的第二个参数是可调用/Closure。通常,此参数的类型和名称为可调用$proceed。

我们必须确保将与原始方法签名相同的参数转发到此可调用对象。

所有其他参数都是原始观察到的方法的参数。插件必须返回与原始函数相同的值,理想情况下返回$proceed(…)或$returnValue=$processed();

然后是$returnValue;对于需要修改$returnValue的情况。

让我们来看看Magento的一个插件实现,该实现在<Magento_DIR>模块分组产品/etc/di.xml文件中指定:

<type name="Magento\Catalog\Model\ResourceModel\Product\Link">
    <plugin name="groupedProductLinkProcessor" type="Magento\GroupedProduct\Model\ResourceModel\Product\Link\RelationPersister" />
</type>

此插件的原始方法以Magento\Catalog\Model\ResourceModel\Product\Link类的deleteProductLink方法为目标:

public function deleteProductLink($linkId) {
    return $this - > getConnection() - > delete($this - > getMainTable(), ['link_id = ?' => $linkId]);
}

around插件的实现是通过Magento\GroupedProduct\Model\ResourceModel\Product\Link\RelationPersister类的aroundDeleteProductLink方法提供的

如以下部分示例所示:

function aroundDeleteProductLink(\Magento\ GroupedProduct\ Model\ ResourceModel\ Product\ Link $subject, \Closure $proceed, $linkId) 
{ // The rest of the code...    $result = $proceed($linkId);    // The rest of the code...    return $result;

推荐文章