Magento 2 How to use plugin.

When building Magento extension, sometime you have to overwrite core function in magento to have custom function. You can use Rewrite function in magento but it is not good solution. If you don’t want to change core class directly, You can use Magento 2 Plugin because it allows editing the behavior of any public class or method by intercepting a function call and running code either before or after or around the function call.

Benefits of Magento 2 Plugin:

You will get the benefits when use Magento 2 Plugin:

  • Forwarding any method call that is used on an object manager controlled object and taken programmatic action
  • Modifying the return value of any method
  • Modifying the arguments of any method
  • Proceeding similarly when other modules are in progress of the same method in the same or predictable way.

To use Magento 2 Plugin you can do

  1. Create Method and testing Controller
  2. Create di.xml file
  3. After Method
  4. Before Method
  5. Around Method

1.Create Method and testing Controller

  • I will create new Method and testing controller , it is more easy to understand. you can create a Magento 2 Module, you can follow the post if you not clear about it . After creating new module , You can create new function in app/code/Vendor/Module/Helper/Data.php
<?php
 
namespace Magebay\Hello\Helper;
 
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;
use Magento\Store\Model\ScopeInterface;

/**
 * Class Data
 * @package Magebay\Hello\Helper
 */
class Data extends AbstractHelper
{
   /**
     * @param string $title
     * @param bool $showDate
     * @return string
     */
    function getWellComeTitle($title = '', $showDate = false) {
        if($showDate)
        {
            $title .= ' To day '.date('Y-m-d');
        }
        return $title;
   }
}
 

Next , We will call function to Controller so you can create new controller in
app/code/Vendor/Module/Controller/Index/

<?php

namespace Magebay\Hello\Controller\Index;

use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;

/**
 * Class Index
 * @package Magebay\Hello\Controller\Index
 */
class TestPlugin extends \Magento\Framework\App\Action\Action
{
    protected $helloHelper;
    public function __construct(
        Context $context,
        \Magebay\Hello\Helper\Data $helloHelper
    )
    {
      parent::__construct($context);
      $this->helloHelper = $helloHelper;
    }

    public function execute()
    {
        $title = $this->helloHelper->getWellComeTitle('Well come to Magebay.com',false);
        echo $title;
    }
}

Clear cache and access link yourdomain.com/hello/index/testPlugin to see result:

2.Create di.xml file

In order to use Plugin , you have to create di.xml file that define Plugin
Create file di.xml in app/code/Vendor/Module/etc

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
      <type name="{ObservedType}">
        <plugin name="{pluginName}"
                type="{PluginClassName}"
                sortOrder="10"
                disabled="false"/>
    </type>
</config>

Explanations:
Required options

  • type name: Enter name of a class or interface that needs to be followed.
  • plugin name: An arbitrary plugin name that identifies a plugin. Also used to merge the configurations for the plugin.
  • plugin type: Fill the name of a plugin’s class or its virtual type. You can refer the following naming convention for this field: \Vendor\Module\Plugin\Plugin.

Optional options:

  • plugin sortOrder: Set order when the plugin calls the other same methods in the process.
  • plugin disabled: That allows you enable or disable a plugin quickly. As the default configuration, the chosen value is false. Use this property to disable core or third-party plugins in your di.xml file.

1. After Method

  • After method will be called after main function fired so you can modify return value in this case. follow example , I will edit file app/code/Magebay/Hello/etc/
 <type name="Magebay\Hello\Helper\Data">
        <plugin name="Magebay_Hello_Helper_Data_Plugin"
                type="Magebay\Hello\Plugin\ModifyText"
                sortOrder="10"
                disabled="false"/>
    </type>
  • As you can see, I define type = Magebay\Hello\Plugin\ModifyText so I will create file ModifyText.php in app/code/Magebay/Hello/Plugin
<?php
/**
 * Created by PhpStorm.
 * User: maiuoc
 * Date: 2019-01-31
 * Time: 10:22 AM
 */
namespace Magebay\Hello\Plugin;
class ModifyText
{
    function afterGetWellComeTitle(\Magebay\Hello\Helper\Data $subject, $result ) {
        echo __METHOD__ . '<br/>';

        return $result . ' Hope you have a nice day';
    }
}

As you can see, I have modified return value, Clear cache and reload link yourdomain.com/hello/index/testPlugin to see changing value :

magento 2 after plugin parameters

2. Before Methods

With before method, you can change arguments for function. I will change change $showDate = true argument getWellComeTitle function in my example: see Code

<?php
/**
 * Created by PhpStorm.
 * User: maiuoc
 * Date: 2019-01-31
 * Time: 10:22 AM
 */
namespace Magebay\Hello\Plugin;
class ModifyText
{
// comment after method to test
   /* function afterGetWellComeTitle(\Magebay\Hello\Helper\Data $subject, $result ) {
        echo __METHOD__ . '<br/>';
        return $result . ' Hope you have a nice day';
    }*/
    function beforeGetWellComeTitle(\Magebay\Hello\Helper\Data $subject, $title = '' , $showDate = true ) {
        echo __METHOD__ . '<br/>';
        $showDate = true; // change date to test 
        return [$title,$showDate];
    }
}

Reload Url yourdomain.com/hello/index/testPlugin, You will see result is updated, date was shown after text.

magento 2 around plugin with parameters

3. Around Method.

This is great feature of plugin , you can do something before and after method fired. I will change argument before method fire and update return value after method fired.

<?php
/**
 * Created by PhpStorm.
 * User: maiuoc
 * Date: 2019-01-31
 * Time: 10:22 AM
 */
namespace Magebay\Hello\Plugin;
class ModifyText
{
// change old functions to test 
   /* function afterGetWellComeTitle(\Magebay\Hello\Helper\Data $subject, $result ) {
        echo __METHOD__ . '<br/>';
        return $result . ' Hope you have a nice day';
    }*/
    /*function beforeGetWellComeTitle(\Magebay\Hello\Helper\Data $subject, $title = '' , $showDate = true ) {
        echo __METHOD__ . '<br/>';
        $showDate = true;
        return [$title,$showDate];
    }*/
    function aroundGetWellComeTitle(\Magebay\Hello\Helper\Data $subject, callable $proceed,$title,$showDate) {
        echo 'Calling' . __METHOD__ . ' -- before',"<br>";
        $showDate = true; // change argument value
        $result = $proceed($title,$showDate);
        echo 'Calling' . __METHOD__ . ' -- after',"<br>";
        $result .= ' Wonderful'; // change return value
        return $result;
    }
}
magento 2 around plugin with parameters

As you can see, I can custom function but I don’t need change original function . I hope it is use for when building extension or do the Magento Project .