aneesahmadweb@gmail.com     03040836207

    Three types of Plugins

    Before Plugin

    After Plugin

    Around Plugin

    To start adding plugin first creade di.xml file and paste below code.

    <config>
      <typename="{ObservedType}">
    <pluginname="{pluginName}"type="{PluginClassName}" sortOrder="1" disabled="false"/>
       </type>
      </config>

    Type name: Its a class, interface, or virtual type, that is observed by our plugin.
    Plugin name: plugin name.
    Plugin type: The name of a plugin’s class or virtual type.
    Plugin sortOrder: Order, in which the plugins calling the same method are to be executed.
    Plugin disabled: Disabled=”true” defines the plugin is disabled.

    Emaple

    Before Plugin

    Step 1: Create di.xml at Ahmad/Work/etc/di.xml.This is declaration of plugin.

    <?xmlversion="1.0"?>
    <configxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <typename="Magento\Checkout\Model\Cart"><pluginname="productcart"type="Ahmad\Work\Plugin\Productcart"sortOrder="1"/></type>
    </config> 

    Step 2: Create Productcart.php as plugin class at Ahmad\Work\Plugin\Productcart.php and addProduct method written as beforeAddProduct method in plugin class.

    <?phpnamespaceVendor\Module\Plugin;classProductcart{publicfunctionbeforeAddProduct(\Magento\Checkout\Model\Cart $subject,$productInfo,$requestInfo= null){$requestInfo['qty'] = 5; // increasing quantity to 5returnarray($productInfo, $requestInfo);}}

    Using this before plugin, when add to cart button clicked with 1 quantity then product will be added in cart with 5 quantity.

    Plugin can only use for

    • Are used to change the behavior of public class functions.

    Plugins cannot be used with:

    1. Final methods and classes
    2. Protected/private methods
    3. Static methods
    4. __construct methods
    5. Virtual types
    6. Objects that are instantiated before Magento\Framework\Interception is bootstrapped

    About Author

    You may also like

    One Response Comment

    • admin  November 27, 2019 at 6:50 am

      Very precise and to the point tutorial.

      Reply

    Leave A Comment

    Please enter your name. Please enter an valid email address. Please enter a message.