Magento – How to use of ‘around’ in plugin, and when it execute

magento2magento2.2

In Magento 2 plugins there are 3 ways to attach your method with any public function.

And around is one of the way.

But I am not sure how to use this and when I used to add my method with around, not sure when it will be executed.

Like before runs before calling of method and after runs before returning of method. So around when will be get executed?

Best Answer

Magento runs the code in around methods before and after their observed methods. Using these methods allow you to override an observed method

Before the list of the original method’s arguments, around methods receive a callable that will allow a call to the next method in the chain. When your code executes the callable, Magento calls the next plugin or the observed function.

Note: If the around method does not call the callable, it will prevent the execution of all the plugins next in the chain and the original method call.

Below is an example of an around method adding behavior before and after an observed method:

namespace My\Module\Plugin;

class ProductAttributesUpdater
{
    public function aroundSave(\Magento\Catalog\Model\Product $subject, callable $proceed)
    {
        $this->doSmthBeforeProductIsSaved();
        $returnValue = $proceed();
        if ($returnValue) {
            $this->postProductToFacebook();
        }
        return $returnValue;
    }
}

Reference: http://devdocs.magento.com/guides/v2.2/extension-dev-guide/plugins.html

Related Topic