Magento 2, PHP

Magento2 Plugin

Magento2 gave very good concept called Plugin

we can do what ever after and before core function and also we have one more called around which will do both before and after below is code which will cover all info

Create a file di.xml in Mymodule/etc/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
   <type name="Magento\Catalog\Block\Product\View">
        <plugin name="inroduct-custom-module" type="Done\Test\Block\Plugin\Product\View" sortOrder="1"/>
    </type>
    <type name="Magento\Catalog\Model\Product">
        <plugin name="getname-test-module" type="Done\Test\Model\Plugin\Product" sortOrder="10"/>
    </type>
</config>

in this i took example of product Model and Product View Block

I used around in Product View block that is any function use prefix around and then make sure 2 parameter should be there is first one is which object your using 2nd one Closure which is retain old return info

<?php
namespace Done\Test\Block\Plugin\Product;

class View 
{ 
    public function aroundGetProduct(\Magento\Catalog\Block\Product\View $subject, \Closure $proceed)
    {
        echo 'Do Some Logic Before <br>';
        $returnValue = $proceed(); // it get you old function return value
        //$name='#'.$returnValue->getName().'#';
        //$returnValue->setName($name);
        echo 'Do Some Logic  After <br>';
        return $returnValue; // if its object make sure it return same object which you addition data
    }
}

In model i Used before and after that is

<?php
namespace Done\Test\Model\Plugin;

class Product
{        
    public function beforeSetName(\Magento\Catalog\Model\Product $subject, $name)
    {
        return array('(' . $name . ')');
    }

     public function afterGetName(\Magento\Catalog\Model\Product $subject, $result)
    {
        return '|' . $result . '|';
    }
}

in this way we can retain old code so if tomorrow Magento core code is updated we will have both new updated code and our custom logic if we directly override then we lost new updated code of that function or file 🙂

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

Tags :