magento2中的Plugin机制--after方法详解
  • Magento
  • 2023-07-24 14:02:38
  • 29980 阅读

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

传递给插件的第一个参数是一个观察到的类型实例。进入插件的第二个参数是观察到的方法的结果,通常调用$result或在从observed方法返回的变量之后调用(如下面的示例:$data)。

所有其他参数都是observe方法的参数。插件必须返回相同类型的$result|$data变量,因为我们可以自由修改值。让我们来看看Magento的一个插件后实现,该实现在模块目录/etc/di.xml文件中指定:

<type name="Magento\Indexer\Model\Config\Data">
    <plugin name="indexerProductFlatConfigGet"         type="Magento\Catalog\Model\Indexer\Product\Flat\Plugin\IndexerConfigData" />
</type>

此插件的原始目标方法是Magento\Indexer\Model\Config\Data类的get方法:

public function get($path = null, $default = null) {    // The rest of the code...    return $data;}

after插件的实现是通过Magento\Catalog\Model\Indexer\Product\Flat\plugin\IndexerConfigData类的afterGet方法提供的,如以下部分示例所示:

public function afterGet(Magento\Indexer\Model\Config\Data, $data, $path = null, $default = null) {    // The rest of the code...    return $data;}

使用插件时应特别小心。虽然它们提供了很大的灵活性,但也很容易引发错误、性能瓶颈和其他不太明显的不稳定性——如果几个插件都在观察相同的方法,情况更是如此。