The around plugin

The around plugin runs around the observed method in a way that allows us to run some code before and after the original method call. This is a very powerful concept, as we get to change the incoming parameters as well as the return value of a function.

When writing the around plugin, there are a few key points to remember:

  1. The first parameter coming into the plugin is the observed type instance.
  2. The second parameter coming into the plugin is a callable/Closure. Usually, this parameter is typed and named as callable $proceed. We must make sure to forward the same parameters to this callable as the original method signature.
  3. All other parameters are parameters of the original observed method.
  4. The plugin must return the same value as the original function, ideally return $proceed(…) or $returnValue = $proceed(); followed by $returnValue; for cases where we need to modify the $returnValue.

Let's take a look at one of Magento's around plugin implementations, the one specified in the <MAGENTO_DIR>module-grouped-product/etc/di.xml file:

<type name="MagentoCatalogModelResourceModelProductLink">
<plugin name="groupedProductLinkProcessor" type="MagentoGroupedProductModelResourceModelProductLinkRelationPersister" />
</type>

The original method of this plugin is targeting the deleteProductLink method of the MagentoCatalogModelResourceModelProductLink class:

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

The implementation of the around plugin is provided via the aroundDeleteProductLink method of the MagentoGroupedProductModelResourceModelProductLinkRelationPersister class, as per the following partial example:

public function aroundDeleteProductLink(
MagentoGroupedProductModelResourceModelProductLink $subject,
Closure $proceed, $linkId) {
// The rest of the code...
$result = $proceed($linkId);
// The rest of the code...
return $result;
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.203.68