How to create Inceptor or Plugin in Magento 2

Written by Mahesh Makwana

Mar 19, 2021

How to create Inceptor or Plugin in Magento 2

Today we learn how to create Inceptor or plugin in Magento 2.  At development time we need to change some function behavior so Magento provides a plugin for it.

A Plugin or Inceptor allows change behavior of any public class or method by intercepting a function call and running code. Plugins are only used for “public methods”.

Types Of Plugins In Magento 2

  • Before Plugin
  • After Plugin
  • Around Plugin

Why we use Interceptors or Extension in Magento 2?

  • we can change the behavior of the same class or method
  • The plugin can be called sequentially according to sort order, so conflict with other plugin class can be avoided.
  • No issue of rewriting the system
  • Customize the same method in different modules.
  • Ability to modify the return value of any public method.
  • Ability to modify the arguments of any public method.
  • Plugins do not conflict with other plugin classes.

The Magento 2 Plugins can’t be used with:

  • Non-public methods (Protected & Private)
  • Static methods
  • Final Methods
  • Final classes
  • Virtual Types
  • Any class that has at least one final public method
  • Objects that are instantiated before Magento\Framework\Interception is bootstrapped
  • __construct and __destruct

Declaring a plugin

A plugin can be declared in the di.xml file in your module.

app/code/VendoreName/ModuleName/etc/di.xml

<config>
    <type name="{ObservedType}">
      <plugin name="{pluginName}" type="{PluginClassName}" sortOrder="1" disabled="false" />
    </type>
</config>
  • type name: A class or interface which the plugin observes.
  • plugin name An arbitrary plugin name that identifies a plugin. Also used to merge the configurations for the plugin.
  • plugin type: The name of a plugin’s class or its virtual type. Use the following naming convention when you specify this element: \Vendor\Module\Plugin\<ClassName>.
  • plugin sortOrder: Plugins that call the same method run them using this order. (Optional)
  • plugin disabled: To disable a plugin, set this element to true. The default value is false. (Optional)
<type name="Dolphin\PluginDemo\Controller\Index\PluginExample">
    <plugin name="demo_plugin" type="Dolphin\PluginDemo\Plugin\PluginDemo" sortOrder="1" disabled="false"  />
</type>

For example, the following code defines type name, we created PluginExample.php file at app/code/Dolphin/PluginDemo/Controller/Index/PluginExample.php

if you don’t know how to create module click here 

<?php

namespace Dolphin\PluginDemo\Controller\Index;

class PluginExample extends \Magento\Framework\App\Action\Action
{
    protected $title;

    public function execute()
    {
        echo $this->setTitle('Welcome Plugin');
        echo $this->getTitle();
    }

    public function setTitle($title)
    {
        return $this->title = $title;
    }

    public function getTitle()
    {
        return $this->title;
    }
}

Find here for more plugins: Magento 2 Extension

1) Before Plugin

  • Before plugin are used whenever we need to change the arguments of the method or need to add some behavior before a method is called.
  • The first method to run is an observed method.
  • Before plugin is called by adding the prefix ‘before’ to the method name and setting the first letter of the original method to capital.
  • It lets you modify the parameters that will be used.
  • Example
<?php

    namespace Dolphin\PluginDemo\Plugin;

    class PluginDemo
    {
        public function beforeSetTitle(\Dolphin\PluginDemo\Controller\Index\PluginExample $subject, $title)
        {
            $title = $title." Before plugin method is calll</br>";
            return [$title];
        }

    }

2) After Plugin

  • After Plugins are used whenever we need to change the arguments of method or need to add some behavior after a method is called.
  • Starts running after the observed method is finished
  • After Plugin is called by adding the prefix ‘after’ to the method name and setting the first letter of the original method to capital.
  • It let you modify the output
  • Responsible for editing the results of an observed method in the right way and must have a return value.
  • Example
<?php

    namespace Dolphin\PluginDemo\Plugin;

    class PluginDemo
    {
        public function afterGetTitle(\Dolphin\PluginDemo\Controller\Index\PluginExample $subject, $result)
        {

            echo "After plugin method call</br>";

            return $result . 'Modify Result';

        }

    }

3) Around Plugin

  • Around Plugin run before and after the observed method.
  • Allows overriding a method
  • Around Plugin change both the arguments and the returned values of the observed method or add behavior before and after the observed method is called.
  • Around listener is called by adding the prefix ‘around’ to the method name and setting the first letter of original method to capital.
  • It must have a return value
  • Example
<?php

    namespace Dolphin\PluginDemo\Plugin;

    class PluginDemo
    {
        public function aroundGetTitle(\Dolphin\PluginDemo\Controller\Index\PluginExample $subject, callable $proceed)
        {
            echo "Around Method Call"
            $result = $proceed();
            echo "Around Method Call over"
            return $result;
        }

    }

Plugins are commonly used in Magento development.

I hope this helps you. For any doubts regarding this topic, please write your doubts in the comments section.

Mahesh Makwana

Author

We can help you with

  • Dedicated Team
  • Setup Extended Team
  • Product Development
  • Custom App Development

Schedule a Developer Interview And Get 7 Days Risk-Free Trial

Fill out This Form and one of Our Technical Experts will Contact you Within 12 Hours.

    Google
    |

    4.8

    Google
    |

    4.8

    Google
    |

    4.9

    Google
    |

    4.8

    Google
    |

    4.9

    Copyright © 2024 DOLPHIN WEB SOLUTION. All rights reserved.

    TO TOP