How to use around plugin in Magento 2?

In this article, we will consider a template that is called interception. You can insert in code dynamically without changing the original class behavior right between the calling code and the needed object. In Magento 2 plugins are used 3 types of interceptors:

  • Before Plugin
  • After Plugin
  • Around Plugin

Today we will show how you can use the around method for your custom development.

In case you have doubts, contact our development specialists and they'll develop any software you need in a defined timeline and budget.

Warning. Using the Around interceptor in your code isn’t the best practice, and we do not advise working with this plugin. Magento recommends avoiding this method and using the before and after plugins instead. For more details about Magento best practices, check the official documentation.

Around Plugin in Magento 2, is a class that allows you to control public methods. One of the input parameters of this method is the function proceed() that runs the original file. As we already mentioned Magento doesn’t recommend using this method because it can turn off the original functionality.

But if you still want to limit the work of the main method, then you can use it. For example, with the help of Magento 2 around plugin, you can make the main method work by conditions or if you want to change both the arguments and the returned values of an original method. Also, with around interceptor, you can add some behavior before and after a primary method. In all other cases, it’s better to use before and after plugins.

Let’s see an example of use around interceptor in code:

<?php
namespace <Vendor>\<Module>\<Example>;
class ProductAttributesUpdater
{
public function aroundSave(\Magento\Catalog\Model\Product $subject, callable $proceed)
{
$someValue = $this->doSmthBeforeProductIsSaved();
$returnValue = null;

        if ($this->canCallProceedCallable($someValue)) {
$returnValue = $proceed();
}

        if ($returnValue) {
$this->postProductToFacebook();
}

        return $returnValue;
}
}

As you can see, we call around method with the prefix around that we add to the needed method. The first letter of the main method is capitalized. After the around plugin, you must add a return value. To form a return value, you have to place a function in sequential order after the $closure parameter.

It’s also important to notice that one of the important values for around plugin in Magento 2 is a sort order. The smaller it is, the first it will be executed. And vise versa, if you will assign a big sort order, it will be executed at the last.

For more detailed information about Magento 2 Around Plugin, read the official Magento documentation.

→ Does it look too complicated? Tell us about your problem, and our team will find a custom solution for you.

How can we help you?

Didn’t you find the answer to your question? We are always happy to help you out.

© 2009-2024 Amasty. All Rights Reserved.