How To Create Plugin in Magento 2

Steps to Create Plugin in Magento 2

Create registration.php

Directory

app/code/vendorName/ModuleName/registration.php

Content for registration.php

<?php
        \Magento\Framework\Component\ComponentRegistrar::register(
            \Magento\Framework\Component\ComponentRegistrar::MODULE,
           'VendorName_ModuleName',
            __DIR__
        );

Create module.xml

Directory

app/code/vendorName/ModuleName/etc/module.xml

Content for module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="VendorName_ModuleName" setup_version="1.0.0">
    </module>
</config>

Create di.xml

Directory

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

Content for di.xml

<?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="Magento\Product\Controller\Index\Index">
           <plugin name="UniqueName" type="VendorName\ModuleName\Plugin\Product\Controller\Example"/>
        </type>
    </config>

Create Example.php

Directory

app/code/vendorName/ModuleName/Plugin/Product/Controller/Example.php

Content for Example.php

<?php

    namespace [VendorName]\[ModuleName]\Plugin\Product\Controller;

    class Example
    {
        public function aroundExecute(
            Index $subject,
            \Closure $proceed
        )
        {
            //You required logic
        }
    }

 

if you are looking for Magento Developer, visit Magento Web Agency.