use-write-use-after-before-around-magento-2-plugins

How To Write and Use After, Before and Around Magento 2 Plugins

by Grace Bui

This article will help you know about Magento 2 Plugins.

According to anyone who works in the industry, inventory management is a key part of any firm that deals with tangible goods. Even those who operate on the internet must keep a tight eye on their inventory levels. If you don’t, you risk running out of goods without realizing it, which could have a negative influence on your business.

Extensions for Magento will help with features like product inventory management and multi-store support. You’ll also be in charge of sales and orders. Inventory transaction log management and inventory update push notifications are among the other capabilities available.

The Definition Of Magento 2 Plugins

A Magento plug-in (or extension, add-on, or whatever you want to call it) is a chunk of PHP code that contains typical functions. It allows you to add new features to your website without having to know how to code.

These extensions give features that Magento does not. The Magento extensions supplier team will examine, build, and test each extension to ensure that it meets your business and market requirements.

The majority of Magento plug-ins are designed to improve the customer’s shopping experience. However, there are several that can help store owners with administration. These modules can help you get more done faster and improve the productivity of your store’s backend.

magento-2-plugins

Magento extensions are being released at an increasing rate. Let’s look at the following section to see which Magento plug you’ll require.

Plugins are a highly strong component of Magento 2:

  • To alter the behavior of public class functions, these variables are used.
  • Final classes, final methods, non-public classes, static methods, construct functions, virtual types, and objects created before MagentoFrameworkInterception is bootstrapped are not supported.

A plugin can be declared in the di.xml file (global, or area-based) of your module with the following structure:

<config>

    <type name="{ObservedType}">

      <plugin name="{pluginName}" type="{PluginClassName}" sortOrder="1" disabled="false" />

    </type>

</config>

Types Of Plugins

As mentioned, there are three types of Magento 2 plugins: before, after, and around.

1. Before plugin

Before the method is invoked, it can be used to update a method’s arguments or add certain behavior. All before methods in Magento are executed before the call to the observed method. The parameters given to the methods were previously accessible to the plugin. These methods must have the same name as the observed method, but with the prefix ‘before’.

Here’s an example of a previous approach for determining whether a buyer of a gift registry item sends greetings to the register’s owner.

public function beforeSaveAddressInformation(

\Magento\Checkout\Model\ShippingInformationManagement $subject,

$cartId,

\Magento\Checkout\Api\Data\ShippingInformationInterface $addressInformation

){

$return = [$cartId, $addressInformation];

$address = $addressInformation->getShippingAddress();

if($address instanceof \Magento\Quote\Api\Data\AddressInterface ){

$extAttributes = $address->getExtensionAttributes();

$giftregistryMessage = $extAttributes->getGiftregistryMessage();

if(!isset($giftregistryMessage) || $giftregistryMessage == ""){

     $extAttributes->setGiftregistryMessage(__("I wish you a wonderful Birthday!"));

}

}

return $return;

}

2. After plugin

After the original method is called, the after method modifies the values returned by the origin method or adds behaviors. Following the completion of the initial method, Magento executes all after methods. Plugins now have access to the original method’s outcome. Plugins have had access to input parameters since Magento 2.2.

This method’s name must have the ‘after’ prefix added to it. Consider the following scenario:

public function afterSaveAddressInformation(

\Magento\Checkout\Model\ShippingInformationManagement $subject,

$result,

$cartId,

\Magento\Checkout\Api\Data\ShippingInformationInterface $addressInformation

){

$address = $addressInformation->getShippingAddress();

if($address instanceof \Magento\Quote\Api\Data\AddressInterface ){

$extAttributes = $address->getExtensionAttributes();

$giftregistryMessage = "From Magenest store: ".$extAttributes->getGiftregistryMessage();

if(!isset($giftregistryMessage) || $giftregistryMessage == ""){

     $extAttributes->setGiftregistryMessage($giftregistryMessage);

}

}

return $result;

}

3.Around plugin

Around methods can modify an original method’s arguments and return values, as well as add behaviors before and after it, is invoked. The prefix ‘around’ is appended to the method’s name.

When you encapsulate a method that accepts arguments, your plugin must accept those arguments as well, and you must transmit them to the proceed callable when you use it. It’s important to match the default arguments and type hints from the method’s original signature.

Example:

public function aroundSaveAddressInformation(

\Magento\Checkout\Model\ShippingInformationManagement $subject,

\Closure $proceed,

$cartId,

\Magento\Checkout\Api\Data\ShippingInformationInterface $addressInformation

) {

$address = $addressInformation->getShippingAddress();

if($address instanceof \Magento\Quote\Api\Data\AddressInterface ){

try{

     $extAttributes = $address->getExtensionAttributes();

     $giftregistryMessage = $extAttributes->getGiftregistryMessage();

     $giftregistryId = $this->_helperCart->getRegistryId();

     /** @var \Magento\Quote\Model\Quote $quote */

     $quote = $this->_quoteRepository->getActive($cartId);

     $quoteId = $quote->getId();

     $tranModel = $this->_tranFactory->create();

     $this->_tranResource->load($tranModel,$quoteId,'quote_id');

     $tranModel->addData([

         'giftregistry_id' => $giftregistryId,

         'message' => $giftregistryMessage,

         'quote_id' => $quoteId

     ]);

     $this->_tranResource->save($tranModel);

}catch (\Exception $exception){

     $this->_logger->critical($exception->getMessage());

}

}

return $proceed($cartId, $addressInformation);

}

Plugin execution order

Before method, around method, origin method, and after method is the execution order of a plugin.

If two plugins apply to the same method, Magento performs the lowest to highest sortOrder method first. If a plugin has many methods, Magento will run the around method in the same plugin until callable() before searching for the next before method in the execution stack after completing the before method(s) in the plugin.

plugin-excecution-order

Source: Magenest

Conclusion

We learned about the purpose of Magento 2 plugins, as well as how to declare, define, and use them in this post. Plugins are widely utilized in Magento 2 development, and we hope that they will help you design the features you require.

You may want to READ about >>> How To Know And Choose The Right Plug In Magento You Need 

BSS Commerce is one of the leading Multi-platform eCommerce solutions and web development services providers in the world. With experienced and certified developers, we commit to bringing high-quality products and services to optimize your business effectively. 

CONTACT NOW to let us know your problems. We are willing to support you at any time.

Next Reading Suggestions

© 2019 BSS Commerce owned by THANH CONG INTER ., JSC. All Rights Reserved.
Business registration certificate no. 0106064469 issued by Hanoi Department of Planning and Investment on 19 December 2019.
Legal Representative: Mr. Nguyen Quang Trung.