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:
- The first parameter coming into the plugin is the observed type instance.
- 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.
- All other parameters are parameters of the original observed method.
- 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;
}